import {
  Component,
  ComponentFactoryResolver,
  HostListener,
  OnDestroy,
  OnInit,
  ViewChild,
  ViewContainerRef
} from "@angular/core";
import {CommService} from "../comm-service";
import {MyhttpService} from "../myhttp.service";
import {LocalStorageService} from "../local-storage-service";
import {FormBuilder, FormGroup} from "@angular/forms";


declare var AMap: any;
declare var $: any;

@Component({
  template: `
    <div class="n_room">
      <div class="lpanel" [style.height]="pagesize.pageh" [style.width]="pagesize.lpanelwstr">
        <div class="arrBtn" (click)="lpanelCtr('l')">
          <i *ngIf="pagesize.lpanelshow" class="fa fa-chevron-left"></i>
          <i *ngIf="!pagesize.lpanelshow" class="fa fa-chevron-right"></i>
        </div>
        <div class="container-fluid" id="lformRoom">
          <div class="row">
            <form class="form-horizontal" role="form">
              <div class="col-lg-12">
                <div class="form-group">
                  <label class="col-lg-3 control-label">查询范围：</label>
                  <div class="col-lg-8 myinput-room">
                    <div class="form-control" style="cursor: pointer;position: relative" (click)="searchTreectr()">
                      {{s_obj.ksgljgidmc}}
                      <div class="myicon">
                        <i class="fa fa-chevron-down" *ngIf="!treeshow"></i>
                        <i class="fa fa-chevron-left" *ngIf="treeshow"></i>
                      </div>
                    </div>
                    <div class="searchtree" *ngIf="treeshow">
                      <div *ngIf="searchtreeObj">
                        <search-tree [o]="searchtreeObj" (outhander)="searchtreeHander($event)"></search-tree>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-lg-12">
                <div class="form-group">
                  <label class="col-lg-3 control-label">查询内容：</label>
                  <div class="col-lg-8">
                    <select class="form-control" name="cxnr" id="cxlxSelect" [(ngModel)]="s_obj.cxlx"
                            (change)="search_n()"></select>
                  </div>
                </div>
              </div>
            </form>
          </div>
          <div class="row">
            <div class="col-lg-12" id="table_rw">
              <div class="portlet box blue">
                <div class="portlet-title">
                  <div class="caption">
                    运送任务列表
                  </div>
                </div>
                <div class="portlet-body">
                  <div class="row">
                    <div class="col-lg-12">
                      <table></table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-lg-12" id="table_zdsb">
              <div class="portlet box blue">
                <div class="portlet-title">
                  <div class="caption">
                    手持终端列表
                  </div>
                </div>
                <div class="portlet-body">
                  <div class="row">
                    <div class="col-lg-12">
                      <table></table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-lg-12" id="table_dzbqsb">
              <div class="portlet box blue">
                <div class="portlet-title">
                  <div class="caption">
                    电子标签列表
                  </div>
                </div>
                <div class="portlet-body">
                  <div class="row">
                    <div class="col-lg-12">
                      <table></table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="rpanel" [style.height]="pagesize.pageh" [style.width]="pagesize.rpanelwstr">
        <div id="mapdiv"></div>
        <div class="carIcon" *ngIf="carBglist.length" style="display: none;">
          <div class="carIcon_item" *ngFor="let item of carBglist">
            <img [src]="item.icon" width="30px;" height="20px"/>
            <span style="display: inline-block;margin-left: 10px">{{item.name}}</span>
          </div>
        </div>
        <!--报警信息 组件容器-->
        <div class="warnmsgDiv">
          <div class="arrBtn_msg" (click)="lpanelCtr('msg')">
            <i *ngIf="!warnmsgshow" class="fa fa-chevron-left"></i>
            <i *ngIf="warnmsgshow" class="fa fa-chevron-right"></i>
          </div>
          <div class="msgroom iecrollkf chromescrollkf">
            <ul class="itemroom" *ngIf="warnmsgList.length">
              <li class="item" *ngFor="let item of warnmsgList">
                <div class="item_sj">{{item.xxsj}}</div>
                <div class="item_nr">{{item.xxnr}}</div>
              </li>
            </ul>
            <div class="nomsg" *ngIf="!warnmsgList.length">
              暂无报警信息
            </div>
          </div>
        </div>
        <!--任务关联的试卷信息-->
        <div class="rw_glsjxx">
          <div class="title">
            <div class="closebtn" title="关闭" (click)="closeWin('rw')">
              <i class="fa fa-close"></i>
            </div>
          </div>
          <div class="body iecrollkf chromescrollkf">
            <table class="table table-bordered">
              <thead>
              <tr>
                <th>标签id</th>
                <th>试卷包名称</th>
                <th>标签登记情况</th>
              </tr>
              </thead>
              <tbody *ngIf="rw_glbqList.length">
              <tr *ngFor="let item of rw_glbqList">
                <td>{{item.bqid}}</td>
                <td>
                  <ng-container *ngIf="item.sjbglzt">
                    <span>{{item.sjbmc}}</span>&nbsp;&nbsp;&nbsp;&nbsp;<span title="试卷包详情" style="cursor: pointer"
                                                                             (click)="showSjbxx(item)">
                  <i class="fa fa-search"></i></span>
                  </ng-container>
                  <ng-container *ngIf="!item.sjbglzt">
                    <span class="text-danger">未绑定试卷包</span>
                  </ng-container>
                </td>
                <td>
                  <span *ngIf="item.bqdjzt=='wdj'" style="color: grey" title="未登记"><i class="fa fa-circle"></i></span>
                  <span *ngIf="item.bqdjzt=='ydj'" style="color: green" title="已登记"><i class="fa fa-circle"></i></span>
                  <span *ngIf="item.bqdjzt=='ddj'" style="color: red" title=""><i class="fa fa-circle"></i></span>
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </div>
        <!-- /end 任务关联的试卷信息-->


        <!--终端关联的试卷信息-->
        <div class="zdsb_glsjxx">
          <div class="title">
            <span>终端扫描试卷包信息详情</span>
            <div class="closebtn" title="关闭" (click)="closeWin('zdsb')">
              <i class="fa fa-close"></i>
            </div>
          </div>
          <div class="body_zdsjxx">
            <div class="has iecrollkf chromescrollkf">
              <table class="table table-bordered" *ngIf="zdsb_glbqList.length">
                <thead>
                <tr>
                  <th width="45%">标签id</th>
                  <th>试卷包名称</th>
                </tr>
                </thead>
                <tbody *ngIf="zdsb_glbqList.length">
                <tr *ngFor="let item of zdsb_glbqList">
                  <td>{{item.bqid}}</td>
                  <td>
                    <ng-container *ngIf="item.sjbglzt">
                      <span>{{item.sjbmc}}</span>&nbsp;&nbsp;&nbsp;&nbsp;<span title="试卷包详情" style="cursor: pointer"
                                                                               (click)="showSjbxx(item)">
                  <i class="fa fa-search"></i></span>
                    </ng-container>
                    <ng-container *ngIf="!item.sjbglzt">
                      <span class="text-danger">未绑定试卷包</span>
                    </ng-container>
                  </td>
                </tr>
                </tbody>
              </table>
            </div>
            <div class="has_no" *ngIf="!zdsb_glbqList.length">
              未扫描到标签
            </div>
          </div>
          <div class="zdsb_ssxx">
            <h4>终端设备实时信息</h4>
            <div class="body_zdssxx">
              <table class="table table-bordered">
                <tr>
                  <th width="100px">终端名称:</th>
                  <td>{{zdsb_ssmsg.scdzmc}}</td>
                </tr>
                <tr>
                  <th>终端id:</th>
                  <td>{{zdsb_ssmsg.id}}</td>
                </tr>
                <tr>
                  <th>电量:</th>
                  <td>{{zdsb_ssmsg.dl}}</td>
                </tr>
                <tr>
                  <th>时间:</th>
                  <td>{{zdsb_ssmsg.sj}}</td>
                </tr>
                <tr>
                  <th>地址:</th>
                  <td>{{zdsb_ssmsg.dzmc}}</td>
                </tr>
              </table>
            </div>
          </div>
        </div>
        <!--/end 终端关联的试卷信息-->


        <!--电子标签 试卷信息-->
        <div class="dzbqsb_xx">
          <div class="title">
            <span>电子标签关联试卷详情</span>
            <div class="closebtn" title="关闭" (click)="closeWin('dzbqsb')">
              <i class="fa fa-close"></i>
            </div>
          </div>
          <div class="body_bqsjxx">
            <div class="has">
              <table class="table table-bordered">
                <thead>
                <tr>
                  <th width="45%">标签id</th>
                  <th>试卷包名称</th>
                </tr>
                </thead>
                <tbody *ngIf="dzbqsb_glbqselfList.length">
                <tr *ngFor="let item of dzbqsb_glbqselfList">
                  <td>{{item.bqid}}</td>
                  <td>
                    <ng-container *ngIf="item.sjbglzt">
                      <span>{{item.sjbmc}}</span>&nbsp;&nbsp;&nbsp;&nbsp;<span title="试卷包详情" style="cursor: pointer"
                                                                               (click)="showSjbxx(item)">
                  <i class="fa fa-search"></i></span>
                    </ng-container>
                    <ng-container *ngIf="!item.sjbglzt">
                      <span class="text-danger">未绑定试卷包</span>
                    </ng-container>
                  </td>
                </tr>
                </tbody>
              </table>
            </div>
            <div class="has_no"></div>
          </div>
          <div class="bqsb_ssxx">
            <h4>电子标签实时信息</h4>
            <div class="body_bqssxx">
              <table class="table table-bordered">
                <tr>
                  <th width="100px">电子标签id:</th>
                  <td>{{dzbqsb_ssmsg.id}}</td>
                </tr>
                <tr>
                  <th>gnss电量:</th>
                  <td>{{dzbqsb_ssmsg.gnssdl}}</td>
                </tr>
                <tr>
                  <th>蓝牙电量:</th>
                  <td>{{dzbqsb_ssmsg.lydl}}</td>
                </tr>
                <tr>
                  <th>时间:</th>
                  <td>{{dzbqsb_ssmsg.sj}}</td>
                </tr>
                <tr>
                  <th>地址:</th>
                  <td>{{dzbqsb_ssmsg.dzmc}}</td>
                </tr>
              </table>
            </div>
          </div>
        </div>

        <!--/end电子标签 试卷信息-->
      </div>
    </div>
    <div class="modal fad" id="send_msgModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
      <div class="modal-dialog smmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">发送消息</h4>
          </div>
          <div class="modal-body">
            <div class="row">
              <form class="form-horizontal" role="form" [formGroup]="formgroup_zdsbmsg">
                <div class="col-lg-12">
                  <div class="form-group">
                    <label class="control-label col-lg-3">消息内容</label>
                    <div class="col-lg-8">
                      <textarea rows="5" class="form-control" formControlName="xxnrCtr"></textarea>
                    </div>
                  </div>
                </div>
              </form>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
            <button type="button" class="btn btn-primary" (click)="sendMsgtoZdsb()">确 定</button>
          </div>
        </div>
      </div>
    </div>
    <div class="modal fad" id="xq_kglbqsjbModal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel">
      <div class="modal-dialog smmodalwidth" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">试卷包信息详情</h4>
          </div>
          <div class="modal-body">
            <div class="row">
              <div class="col-lg-12" *ngIf="xqobj_sjbxx">
                <xq-form [o]="xqobj_sjbxx"></xq-form>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">关 闭</button>
          </div>
        </div>
      </div>
    </div>


  `,
  styles: [
    ".n_room{overflow-x: auto;overflow-y: hidden;position: relative;margin: 0px auto}",
    ".n_room>.lpanel{position: absolute;left:0px;top: 0px;overflow-y: hidden;background-color: #ffffff;}",
    ".n_room>.rpanel{position: relative;margin-left: 475px}",
    //左侧 z-index =100要大于form的
    ".lpanel>.arrBtn{position: absolute;z-index: 100; top: 5px;right: 0px; width: 20px;height: 50px;line-height: 50px;text-align: center;color: #ffffff;background-color: #3598DC; cursor: pointer}",
    ".lpanel>#lformRoom{padding-top: 20px}",
    ".myinput-room{position: relative;height: 34px;}",
    ".myicon{position: absolute;width: 30px;height: 30px;right: 5px;top: 0px;text-align: center;padding-top: 5px;cursor: pointer}",
    ".searchtree{z-index: 400;width: 100%;background-color: #fff; position: absolute;top: 35px;left: 0px;}",
    "#table_rw{display: none}",
    "#table_zdsb{display: none}",
    "#table_dzbqsb{display: none}",
    // 右侧
    "#mapdiv{width: 100%;height: 100%}",
    ".carIcon{position: absolute;left: 80px;top: 20px;background-color: grey;color: #ffffff}",
    ".carIcon>.carIcon_item{padding: 5px 10px}",
    // 报警信息
    ".warnmsgDiv{overflow: hidden;position: absolute;bottom: 0px;right: 0px;width: 250px;height: 300px;  padding-right: 20px;}",
    ".arrBtn_msg{position: absolute;z-index: 100; bottom: 125px;right: 0px; width: 20px;height: 50px;line-height: 50px;text-align: center;color: #ffffff;background-color: #3598DC; cursor: pointer}",
    ".msgroom{overflow-y: auto;overflow-x: hidden;width:230px;height: 300px;  background-color: rgba(0, 0, 0, 0.8);border-radius: 8px;display: none}",
    ".msgroom>.itemroom{list-style: none;margin: 0px 10px 10px}",
    ".msgroom>.nomsg{text-align: center;font-size: 20px;color: red;line-height: 300px}",
    ".item{width: auto;padding: 5px 15px;background-color: rgba(44, 238, 245, 0.3);margin-top: 10px;color: #ffffff}",
    ".item>.item_sj{color: #30F9FD}",
    ".item>.item_nr{font-size: 15px;padding: 5px 0px; }",
    // 运送任务关联的标签，关联的试卷信息
    ".rw_glsjxx{position: absolute;top: 0px;right: 0px;width: 450px;height: auto; overflow:hidden; background-color: rgba(0, 0, 0, 0.8);border-radius: 8px;display: none}",
    ".rw_glsjxx>.title{height: 30px;line-height: 30px;padding-left: 10px;font-size: 18px;color: yellow; position: relative}",
    ".rw_glsjxx>.body{height: 370px;overflow-y: auto;}",
    ".rw_glsjxx>.title>.closebtn{position: absolute;right: 5px;top: 5px;width: 20px;height: 20px;line-height: 20px;text-align: center;background-color: #0050C3;border-radius: 50%;color: rgb(208, 230, 254);cursor: pointer}",
    ".rw_glsjxx table{color: #ffffff}",
    // 终端设备关联的标签，关联的试卷信息
    ".zdsb_glsjxx{position: absolute;top: 0px;right: 0px;width: 450px;height: auto; overflow:hidden; background-color: rgba(0, 0, 0, 0.8);border-radius: 8px;display: none}",
    ".zdsb_glsjxx>.title{height: 30px;line-height: 30px;padding-left: 10px;font-size: 18px;color: yellow; position: relative}",
    ".zdsb_glsjxx>.body_zdsjxx{height: 250px;position: relative}",
    ".zdsb_glsjxx>.zdsb_ssxx{width: 100%;height: auto;margin-top: 20px}",
    ".zdsb_glsjxx>.title>.closebtn{position: absolute;right: 5px;top: 5px;width: 20px;height: 20px;line-height: 20px;text-align: center;background-color: #0050C3;border-radius: 50%;color: rgb(208, 230, 254);;cursor: pointer}",
    ".zdsb_glsjxx>.body_zdsjxx>.has{height: 250px;overflow-y: auto;}",
    ".zdsb_glsjxx>.body_zdsjxx>.has_no{position: absolute;left: 0px;top: 0px; width: 100%; height: 250px;line-height: 250px;text-align: center;color: red}",
    ".zdsb_glsjxx table{color: #ffffff}",
    ".zdsb_ssxx>h4{color: yellow;padding-left: 10px}",
    ".zdsb_ssxx>.body_zdssxx{width: 100%;height: 200px;}",
    ".body_zdssxx table{color: #ffffff}",
    // 电子标签 实时信息
    ".dzbqsb_xx{position: absolute;top: 0px;right: 0px;width: 450px;height: auto; overflow:hidden; background-color: rgba(0, 0, 0, 0.8);border-radius: 8px;display: none}",
    ".dzbqsb_xx>.title{height: 30px;line-height: 30px;padding-left: 10px;font-size: 18px;color: yellow; position: relative}",
    ".dzbqsb_xx>.body_bqsjxx{height: 100px;position: relative}",
    ".dzbqsb_xx>.bqsb_ssxx{width: 100%;height: auto}",
    ".dzbqsb_xx>.title>.closebtn{position: absolute;right: 5px;top: 5px;width: 20px;height: 20px;line-height: 20px;text-align: center;background-color: #0050C3;border-radius: 50%;color: rgb(208, 230, 254);;cursor: pointer}",
    ".dzbqsb_xx>.body_bqsjxx>.has{height: 100px;overflow-y: auto}",
    ".dzbqsb_xx table{color: #ffffff}",
    ".bqsb_ssxx>h4{color: yellow;padding-left: 10px}",
    ".bqsb_ssxx>.body_bqssxx{width: 100%;height: 200px}",
    ".body_bqssxx table{color: #ffffff}"
  ]
})
export class SsgJComponent implements OnInit, OnDestroy {
  userinfo: any;
  sysBase: string;
  pagesize: any = {
    pageh: "0px",  // 整个页面的高度，自适应浏览器的窗口高度
    lpanelwinit: 475, // 左侧宽度
    lpanelwstr: "475px",
    rpanelwinit: 0, // 右侧宽度，自适应浏览器的窗口宽度
    rpanelwstr: "0px",
    lpanelshow: true
  };
  map: any;   // 地图实例
  mapwin: any;  // 地图提示窗口实例
  geocoder: any; // 逆定理编码实例，经纬度获取地址

  s_obj: any = {
    ksgljgidmc: "",
    ksgljgid: "",
    cxlx: "sjysrw", // sjysrw--运送任务列表 dzbqsb--电子标签设备列表 sczdsb --手持终端设备列表
    ksjhbh: ""
  };
  treeshow: boolean = false;
  searchtreeObj: any;
  // key 只会有 当前查询类型的内容的id_n
  allroadPointer: any = {};  // key--id(运送任务编号/终端id/标签id)   value: 实时节点对象数组
  allroadPointer_buffer: any = {};  //key-- jd/wdjson字符串 (去重使用)
  allroadMsg: any = {}; // key -id   value:  object类型，运送任务信息
  allroadMaker: any = {}; // key--id  value : 车辆marker对象
  allroadPolyline: any = {}; //key -id   value: 路径对象,用于更新轨迹
  // 定位实时轨迹中，地图中心点的，（如果有点击的marker，以点击的 nowclickcar 为中心点），如果没有，则用最后一个id_n的最后一个轨迹点做地图中心点
  lastroad_id_N: string; //功能去掉了
  nowclickcar: any;  // 1： lastroad_id_N一起定位地图中心点（功能去掉） 2： 信息窗口
  allroadclickcar_clickListener: any = {}; // key --id  value:对应的车的绑定事件对象
  polylineColor: any = {
    "sjysrw": "#23D96E", // 任务轨迹线颜色
    "sczdsb": "#23D96E", // 终端轨迹线颜色
    "dzbqsb": "#23D96E", // 标签轨迹线颜色
    "gs": "#BCBCBC", // 任务/终端/标签  过时轨迹线颜色
    "highter": "#0050C3",  // 任务/终端/标签  高亮轨迹线颜色
  };
  timeRange: number = 600000; // ms (毫秒)  过时的判断依据
  carImage: any = {
    //"rw1": "assets/img/sjgz/car_green.png",  // 目的地附近 （距离目的地距离小于1000米，速度 不判断）
    "rw1": "assets/img/sjgz/car_green.png",  // 目的地附近 （距离目的地距离小于1000米，速度 不判断）
    //"rw2": "assets/img/sjgz/car_blue.png", // 正常行驶  （速度>0, 距离目的地1000米以上）
    "rw2": "assets/img/sjgz/car_green.png", // 正常行驶  （速度>0, 距离目的地1000米以上）
    //"rw3": "assets/img/sjgz/car_red.png", // 暂停  （速度=0）
    "rw3": "assets/img/sjgz/car_green.png", // 暂停  （速度=0）
    "rw4": "assets/img/sjgz/car_gs.png",  // 过时 （最后一个点的时间  和   电脑时间相差 1000ms 以上）
    //"rw5": "assets/img/sjgz/car_highter.png",  // 高亮
    "rw5": "assets/img/sjgz/car_blue.png",  // 高亮

    "zdsb1": "assets/img/sjgz/car_green.png",  //
    // "zdsb2": "assets/img/sjgz/car_blue.png", // 正常行驶  （速度>0）
    "zdsb2": "assets/img/sjgz/car_green.png", // 正常行驶  （速度>0）
    //"zdsb3": "assets/img/sjgz/car_red.png",  // 暂停  （速度=0）
    "zdsb3": "assets/img/sjgz/car_green.png",  // 暂停  （速度=0）
    "zdsb4": "assets/img/sjgz/car_gs.png",  //过时 （最后一个点的时间  和   电脑时间相差 1000ms 以上）
    //"zdsb5": "assets/img/sjgz/car_highter.png",  // 高亮
    "zdsb5": "assets/img/sjgz/car_blue.png",  // 高亮

    "bqsb1": "assets/img/sjgz/bqsb_green.png",
    //"bqsb2": "assets/img/sjgz/bqsb_blue.png", // 正常行驶  （速度>0）
    "bqsb2": "assets/img/sjgz/bqsb_green.png", // 正常行驶  （速度>0）
    //"bqsb3": "assets/img/sjgz/bqsb_red.png",// 暂停  （速度=0）
    "bqsb3": "assets/img/sjgz/bqsb_green.png",// 暂停  （速度=0）
    "bqsb4": "assets/img/sjgz/bqsb_gs.png",//过时 （最后一个点的时间  和   电脑时间相差 1000ms 以上）
    //"bqsb5": "assets/img/sjgz/bqsb_highter.png", // 高亮
    "bqsb5": "assets/img/sjgz/bqsb_blue.png", // 高亮
  };
  carBglist: any = [{
    code: "1",
    name: "到达目的附近（1000米内）",
    icon: "assets/img/sjgz/car_green.png",
    icon_dzsb: "",
    icon_bqsb: ""
  }, {
    code: "2",
    name: "正在行驶",
    icon: "assets/img/sjgz/car_blue.png",
    icon_dzsb: "",
    icon_bqsb: ""
  }, {
    code: "3",
    name: "暂停",
    icon: "assets/img/sjgz/car_red.png",
    icon_dzsb: "",
    icon_bqsb: ""
  }, {
    code: "4",
    name: "长时间无轨迹数据",
    icon: "assets/img/sjgz/car_gs.png",
    icon_dzsb: "",
    icon_bqsb: ""
  }];
  // 定时器请求 实时轨迹
  lockid: any;
  intervalnum: number = 60000;
  // 详情的时候，高亮（图标+ 轨迹线）+ 根据cfdMarker、mddMarker,viewpolygon定位地图中心
  // 取消高亮的时候， 非高亮（图标+轨迹线） + 取消根据cfdMarker、mddMarker,viewpolygon,点的车 定位地图中心
  cfdMarker: any;
  mddMarker: any;
  viewpolygon: any;
  caozuoid_n_highter: string = ""; // 任务编号/  终端id / 电子标签id  处理高亮轨迹先+ 图标
  //#############报警信息
  warnmsgshow: boolean = false;
  s_obj_warnmsg: any = {
    ksjhbh: "",
    //传递规则
    // 第一次请求传"", 返回消息为空，返回服务器时间
    //第二次请求使用缓存中的服务器时间
    //以后的请求，从请求到数据开始以后，都用接口返回的消息中的时间。  请求到数据之前，一直用服务器时间
    lssj: ''
  };
  warnmsgList: any[] = [];
  lockid_warnmsg: any;
  intervalnum_warnmsg: number = 60000;

  //#######向终端发送消息
  caozuoid_n: string = ""; // 终端id ，给终端发送消息
  formgroup_zdsbmsg: FormGroup; // 向终端设备发送消息

  //######## 任务/终端 关联的标签状态， 标签关联的试卷包信息
  caozuoid_n_glsbxx: string = "";
  allroadglbqList_cache = {}; //key -id    value:  上报标签id列表(终端扫描到的)，string[]. 最新的实时估计返回的，每次会被更新掉
  rw_glbqListbase: any[] = []; // 点击的任务关联的 标签id, 每个任务是固定的
  rw_glbqList: any[] = [];//   双向绑定显示页面用的

  zdsb_glbqList: any[] = []; // 双向绑定显示页面用的
  zdsb_ssmsg: any = {
    scdzmc: "", //终端名称
    id: "",  // 终端ID
    dl: "",  // 终端电量
    sj: "",  // 时间
    dzmc: ""  // 实时位置
  };  // 点击详情的终端，实时信息


  dzbqsb_glbqselfList: any[] = []; // 双向绑定页面使用
  dzbqsb_ssmsg: any = {
    id: "",  //id
    gnssdl: "", //gnss电量
    lydl: "",  // 蓝牙电量
    sj: "", // 时间
    dzmc: ""  // 地址
  }


  xqobj_sjbxx: any; // 试卷包信息详情
  cllx: string = 'jp'; // 处理类型 jp-纠偏   ph--平滑
  graspobj: any;


  /**
   * 加载 机构树
   */
  initsearchTree(): void {
    this.searchtreeObj = {
      treetype: "cstree",//树选型
      nodelx: "ksgljg",//树节点类型
      id: this.userinfo.csid,//场所编号
      type: this.userinfo.cslx,//机构类型
      text: this.userinfo.csmc,//场所名称
      treeheight: 400,
      clickroot: false
    };
    this.s_obj.ksgljgidmc = this.userinfo.csmc;
    this.s_obj.ksgljgid = this.userinfo.csid;
    this.search_n();
  }

  /**
   * 点击搜索树
   * @param e
   */
  searchtreeHander(e: any): void {
    const type = e.type;
    if (type === "clicknode") {
      const data = e.data;
      const nodeid = data.nodeid;
      this.s_obj.ksgljgid = nodeid; // 考试管理机构id/ 标准化考点id//场所编号
      this.s_obj.ksgljgidmc = data.nodetext;
      this.treeshow = false;
      this.search_n();
    }
  }

  /**
   * 搜索 任务/手持终端设备/电子标签设备
   */
  search_n(): void {
    const cxlx = this.s_obj.cxlx;
    switch (cxlx) {
      case "sjysrw":
        $("#table_rw").show();
        $("#table_zdsb").hide();
        $("#table_dzbqsb").hide();
        this.getall_rw();
        break;
      case "sczdsb":
        $("#table_rw").hide();
        $("#table_zdsb").show();
        $("#table_dzbqsb").hide();
        this.getall_zdsb();
        break;
      case "dzbqsb":
        $("#table_rw").hide();
        $("#table_zdsb").hide();
        $("#table_dzbqsb").show();
        this.get_bqsb();
        break;
    }
  }

  /**
   * 获取所欲的运送任务
   * 1： 表格生成--客户端分页
   * 2： 实时轨迹处理
   */
  getall_rw(): void {
    const url = "sjgz/gjcx/ysrwlb";
    this.itservice.kwPtPost(url, {
      ksgljgid: this.s_obj.ksgljgid,
      ksjhbh: this.s_obj.ksjhbh,
      rwwczt: "",  // 	任务完成状态
      pageNum: 1,
      pageSize: 9999
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const ysrwList = resp.ysrwList;
            if (ysrwList && ysrwList.length) {
              this.inittable_rwClient(ysrwList);
              this.handreqTrailData(ysrwList);
            } else {
              this.inittable_rwClient([]);
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getall_rw();
        }
      });
    });
  }

  /**
   * 获取所欲的手持终端设备
   * 1： 表格生成--客户端分页
   * 2： 实时轨迹处理
   */
  getall_zdsb(): void {
    const url = "sjgz/gjcx/sczdsblb";
    this.itservice.kwPtPost(url, {
      ksgljgid: this.s_obj.ksgljgid,
      sfqy: "", // 是否启用
      pageNum: 1,
      pageSize: 9999
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const sczdList = resp.sczdList;
            if (sczdList && sczdList.length) {
              this.inittable_zdsbClient(sczdList);
              this.handreqTrailData(sczdList);
            } else {
              this.inittable_zdsbClient([]);
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getall_rw();
        }
      });
    });
  }

  /**
   * 获取所欲的电子标签
   * 1： 表格生成--客户端分页
   * 2： 实时轨迹处理
   */
  get_bqsb(): void {
    const url = "sjgz/gjcx/dzbqsblb";
    this.itservice.kwPtPost(url, {
      ksgljgid: this.s_obj.ksgljgid,
      ksjhbh: this.s_obj.ksjhbh,
      sfqy: "", // 是否启用
      pageNum: 1,
      pageSize: 9999
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const dzbqList = resp.dzbqList;
            if (dzbqList && dzbqList.length) {
              this.inittable_bqsbClient(dzbqList);
              this.handreqTrailData(dzbqList);
            } else {
              this.inittable_bqsbClient([]);
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.getall_rw();
        }
      });
    });
  }

  /**
   * 查询内容切换/ 查询入参变化
   *
   * 处理轨迹请求体数据
   */
  handreqTrailData(list: any): void {
    if (this.lockid) {
      clearInterval(this.lockid);
    }
    //this.map.clearMap();// 清楚地图所有覆盖物，信息窗口不属于覆盖物
    // 清除 除了  cfdmarker  mmdmarker  viewpolygon 外的所有覆盖物
    const carmarker: any[] = [], polyline: any[] = [] = [];
    for (const id_n in this.allroadMaker) {
      if (this.allroadMaker[id_n]) {
        carmarker.push(this.allroadMaker[id_n]);
      }
    }
    for (const id_n in this.allroadPolyline) {
      if (this.allroadPolyline[id_n]) {
        polyline.push(this.allroadPolyline[id_n]);
      }
    }
    this.map.remove(carmarker.concat(polyline));
    // 窗口要关闭
    this.mapwin.close();
    // 出发地 ，目的地，地图围要隐藏
    this.cfdMarker.hide();
    this.mddMarker.hide();
    this.viewpolygon.hide();
    // 每次切换查询内容， 让这些还原。保证里面存放的都是  查询内容对应的相关数据
    this.allroadMsg = {};
    this.allroadPointer = {};
    this.allroadPointer_buffer = {};
    this.allroadMaker = {};
    this.allroadPolyline = {};
    this.allroadglbqList_cache = {};
    this.allroadclickcar_clickListener = {};
    // 任务关联电子标签--试卷信息的弹框也隐藏
    $(".rw_glsjxx").hide();
    $(".zdsb_glsjxx").hide();
    $(".dzbqsb_xx").hide();
    this.caozuoid_n = "";
    this.caozuoid_n_highter = "";
    this.caozuoid_n_glsbxx = "";
    //  #######  还原地图信息  end  ############
    const cxlxv = this.s_obj.cxlx;
    const ids_N: any[] = [];
    list.forEach((item) => {
      let id_N: string = "";
      if (cxlxv == "sjysrw") {
        id_N = item.ysrwbh;
      } else if (cxlxv == "sczdsb" || cxlxv == "dzbqsb") {
        id_N = item.id;
      }
      ids_N.push(id_N);
      this.allroadMsg[id_N] = item;
      this.allroadPointer[id_N] = [];
      this.allroadPointer_buffer[id_N] = [];
      this.allroadMaker[id_N] = null;
      this.allroadPolyline[id_N] = null;
      this.allroadglbqList_cache[id_N] = [];
      this.allroadclickcar_clickListener[id_N] = null;
    });
    // this.lastroad_id_N = ids_N[ids_N.length - 1];


    //切换以后，这个请求肯定是 cxnr对应的
    this.getallRoadTrailing(ids_N, cxlxv, "init");
    // 切换以后，上一个的延迟定时请求可能会请求一次。需要做处理!!!!!!!!!!!
    this.lockid = setInterval(() => {
      this.getallRoadTrailing(ids_N, cxlxv, "reload");
    }, this.intervalnum);
  }


  /**
   *获取实时轨迹数据
   * @param ids_N
   * @param {string} cxlxv
   * 运送任务编号数组  sjysrw
   * 终端设备id 数组   sczdsb
   * 标签设备id 数组   dzbqsb
   * actionflag
   * init--第一次请求某类数据
   * reload---定时器请求的
   */
  getallRoadTrailing(ids_N: any, cxlxv: string, actionflag: string): void {
    const cxxxListv = ids_N.map((id_n) => {
      const pointerarr = this.allroadPointer[id_n];
      return {
        id: id_n,
        lssj: pointerarr.length > 0 ? pointerarr[pointerarr.length - 1].sj : ""
      }
    });
    const reqobj = {
      cxlx: cxlxv,
      cxxxList: cxxxListv
    };
    if (actionflag == "init") {
      this.commservice.blockUI({
        boxed: true,
        message: "查询中...",
        zIndex: 10051,
        overlayColor: "#67809F"
      });
    }
    const url = "sjgz/gjcx/cxssgj";
    this.itservice.kwPtPost(url, reqobj).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const allroadPointerList = resp.ssgjcxList ? resp.ssgjcxList : [];
            // ########### 切换以后，上一个的延迟定时请求可能会请求一次。需要做处理
            if (allroadPointerList && allroadPointerList.length) {
              const oneroad_obj = allroadPointerList[0];
              if (oneroad_obj) {
                const id_n = oneroad_obj.id;
                if (this.allroadPointer[id_n] == null) {
                  // 切换以后，上一个的延迟定时请求可能会请求一次。需要做处理
                  this.commservice.warn("切换以后，上一个的延迟定时请求可能会请求一次。需要做处理", "", "");
                  return;
                }
              }
            }
            //################ 处理轨迹， 上报标签id
            allroadPointerList.forEach((item) => {
              const id_n = item.id;
              const oneroadPointerarr = item.ssgjList ? item.ssgjList : [];  // 每辆车实时点数组,可能是Null
              const rwglsblx = item.rwglsblx ? item.rwglsblx : ""; //任务关联设备类型  sczdsb  dzbqsb  null
              const sbbqidListv = item.sbbqidList ? item.sbbqidList : []; // id_n 对应的上报的标签id
              const rwwcztv = item.rwwczt;  // 	任务完成状态
              //任务状态是 1 ==已完成的， 要把他的轨迹和marker清空
              if (rwwcztv == 1) {
                const removeFgw = [];
                if (this.allroadMaker[id_n]) {
                  removeFgw.push(this.allroadMaker[id_n]);
                }
                if (this.allroadPolyline[id_n]) {
                  removeFgw.push(this.allroadPolyline[id_n]);
                }
                this.map.remove(removeFgw);
                // 信息窗口隐藏
                this.mapwin.close();
                // 处理 任务/终端 标签试卷包的信息
                this.allroadglbqList_cache[id_n] = [];
                switch (cxlxv) {
                  case "sjysrw": {
                    if (this.caozuoid_n_glsbxx && this.caozuoid_n_glsbxx == id_n) {
                      this.hander_bqzt('rw', id_n, "reload");
                    }
                  }
                    break;
                  case "sczdsb": {
                    if (this.caozuoid_n_glsbxx && this.caozuoid_n_glsbxx == id_n) {
                      this.hander_bqzt('zdsb', id_n, "reload");
                    }
                  }
                    break;
                }
              } else {
                this.allroadglbqList_cache[id_n] = sbbqidListv;  // 每次请求回来数据都会更新掉
                //###### 临时处理
                // const oneroadPointerarr_cl = oneroadPointerarr.filter((item) => {
                //   return Number(item.fxj) != 0;
                // });
                // const oneroadPointerarr_sigle: any[] = [];
                // oneroadPointerarr_cl.forEach((item) => {
                //   const obj = {
                //     jd: item.jd,
                //     wd: item.wd
                //   };
                //   const jsonstr = JSON.stringify(obj);
                //   if (this.allroadPointer_buffer[id_n].indexOf(jsonstr) == -1) {
                //     this.allroadPointer_buffer[id_n].push(jsonstr);
                //     oneroadPointerarr_sigle.push(item);
                //   }
                // });
                //#########end  临时处理
                // beigin
                this.addTrail(id_n, cxlxv, oneroadPointerarr, rwglsblx);
                oneroadPointerarr.forEach((pointer) => {
                  this.allroadPointer[id_n].push(pointer);  // 实时点数据前端记录
                });
                //end
              }
            });
          }
        } else {
          this.getallRoadTrailing(ids_N, cxlxv, actionflag);
        }
      });
    });
  }

  /**
   *
   * @param {string} id_n
   * @param {string} cxlxv
   *  运送任务编号数组  sjysrw
   * 终端设备id 数组   sczdsb
   * 标签设备id 数组   dzbqsb
   * @param oneroadPointerarr, id_n 对应的   实时轨迹数组，可能是[]
   */
  addTrail(id_n: string, cxlxv: string, oneroadPointerarr: any, rwglsblx: string): void {
    const that = this;
    let lastpointer: any; //id 实时最后一个坐标点
    if (oneroadPointerarr.length) {
      lastpointer = oneroadPointerarr[oneroadPointerarr.length - 1];
    } else {
      const cachePointerList = this.allroadPointer[id_n];
      if (cachePointerList.length) {
        lastpointer = cachePointerList[cachePointerList.length - 1];
      } else {
        lastpointer = null;
      }
    }
    //id_n 实时轨迹，自始至终都没有一个点，图标 估计均不做处理
    if (!lastpointer) {
      return
    }
    if (!lastpointer.jd || !lastpointer.wd) {
      // 处理后端返回的错误数据
      return
    }
    this.commservice.warn("轨迹最后一个点所属id_n", id_n, lastpointer);

    const flag = this.getTimerange(lastpointer.sj);
    //############ 处理轨迹对象 ##############
    // 轨迹颜色
    //1: 规定的，2 过时的 3 高亮的
    let initpolylineColor: string = "";
    if (this.caozuoid_n_highter && this.caozuoid_n_highter == id_n) {
      initpolylineColor = this.polylineColor["highter"];
    } else {
      if (flag) {
        initpolylineColor = this.polylineColor["gs"];
      } else {
        initpolylineColor = this.polylineColor[cxlxv];  // 各自查询类型定义的颜色
      }
    }
    const id_n_Polyline = this.allroadPolyline[id_n];
    if (!id_n_Polyline) {
      this.allroadPolyline[id_n] = new AMap.Polyline({
        map: this.map,
        strokeColor: initpolylineColor,
        strokeOpacity: 1,
        strokeWeight: 5,
        strokeStyle: "solid",
        strokeDasharray: [10, 5],
        zIndex: 50,  //默认值是 50
      });
    }
    this.allroadPolyline[id_n].setOptions({
      strokeColor: initpolylineColor
    });
    //######### 处理车对象 ################
    const markobj: any = {}; // id  实时车辆信息对象
    markobj["id_n"] = id_n;//
    markobj["markerlx"] = cxlxv;
    markobj["fxj"] = this.commservice.removeSpace(false, lastpointer.fxj);//mqtt中信息中，方向角
    markobj["sd"] = this.commservice.removeSpace(false, lastpointer.sd);//mqtt中信息中，车速 km/h
    markobj["sj"] = this.commservice.removeSpace(false, lastpointer.sj); // 时间
    markobj["dl"] = this.commservice.removeSpace(false, lastpointer.dl); // 终端电量
    markobj["gnssdl"] = this.commservice.removeSpace(false, lastpointer.gnssdl); // gnssdl电量
    markobj["lydl"] = this.commservice.removeSpace(false, lastpointer.lydl); // lydl 电量
    markobj["position"] = [lastpointer.jd, lastpointer.wd];
    const oneroadmsg = this.allroadMsg[id_n];
    markobj["distantv"] = this.getGetDisance(lastpointer.jd, lastpointer.wd, oneroadmsg.mddjd, oneroadmsg.mddwd);// 计算距离目的地距离, 现在没有目的地经纬度
    // 图标颜色
    //1 规定的 2 过时的 3 高亮的
    let iconurl: string = "";
    if (this.caozuoid_n_highter && this.caozuoid_n_highter == id_n) {
      if (cxlxv == "sjysrw") {
        markobj["ysrwmc"] = oneroadmsg.ysrwmc;
        markobj["mddmc"] = oneroadmsg.mddmc;
        iconurl = this.carImage["rw5"];
      } else if (cxlxv == "sczdsb") {
        markobj["scdzmc"] = oneroadmsg.scdzmc;
        iconurl = this.carImage["zdsb5"];
      } else if (cxlxv == "dzbqsb") {
        iconurl = this.carImage["bqsb5"];
      }
    } else {
      switch (cxlxv) {
        case "sjysrw": {
          markobj["ysrwmc"] = oneroadmsg.ysrwmc;
          markobj["mddmc"] = oneroadmsg.mddmc;
          if (flag) {
            iconurl = this.carImage["rw4"];
          } else {
            if (markobj["distantv"] < 1000) {
              iconurl = this.carImage["rw1"];
            } else {
              if (Number(markobj["sd"])) {
                iconurl = this.carImage["rw2"];
              } else {
                iconurl = this.carImage["rw3"];
              }
            }
          }
        }
          break;
        case "sczdsb": {
          markobj["scdzmc"] = oneroadmsg.scdzmc;
          if (flag) {
            iconurl = this.carImage['zdsb4'];
          } else {
            if (Number(markobj["sd"])) {
              iconurl = this.carImage['zdsb2'];
            } else {
              iconurl = this.carImage["zdsb3"];
            }
          }
        }
          break;
        case "dzbqsb": {
          if (flag) {
            iconurl = this.carImage['bqsb4'];
          } else {
            if (Number(markobj["sd"])) {
              iconurl = this.carImage['bqsb2'];
            } else {
              iconurl = this.carImage["bqsb3"];
            }
          }
        }
          break;
      }
    }
    markobj["iconurl"] = iconurl;
    const id_n_marker = this.allroadMaker[id_n];
    if (!id_n_marker) {
      this.allroadMaker[id_n] = new AMap.Marker({
        map: that.map,
        //position: markobj.position,
        offset: new AMap.Pixel(-17, -9),
        //angle: Number(markobj.fxj) + 90 + 180,
        icon: new AMap.Icon({
          //34x18px
          image: markobj.iconurl,
          imageOffset: new AMap.Pixel(0, 0),
          imageSize: new AMap.Size(34, 18)
        }),
        zIndex: 100,  //默认值是100
        extData: markobj
      });
    }
    this.allroadMaker[id_n].setIcon(new AMap.Icon({
      image: markobj.iconurl,
      imageOffset: new AMap.Pixel(0, 0),
      imageSize: new AMap.Size(34, 18)
    }));
    // ############# 处理实时轨迹  ############
    const cachePointerList = this.allroadPointer[id_n];
    let oneroadPointerarr_now = oneroadPointerarr.slice();
    if (cachePointerList.length) {
      oneroadPointerarr_now = cachePointerList.concat(oneroadPointerarr_now); // 历史的点也加进去
    }
    let linedata = oneroadPointerarr_now.map(function (value) {
      return [value.jd, value.wd];
    });
    //linedata = this.handPH(linedata);
    this.allroadPolyline[id_n].setPath(linedata);


    // if (cxlxv == "sjysrw") {
    //   if (rwglsblx == "sczdsb") {
    //     this.cllx = "jp";
    //   } else if (rwglsblx == "dzbqsb") {
    //     this.cllx = "ph";
    //   }
    // } else {
    //   // 终端/ 标签页
    //   this.cllx = "jp";
    // }
    // if (this.cllx == "ph") {
    //   let linedata = oneroadPointerarr_now.map(function (value) {
    //     return [value.jd, value.wd];
    //   });
    //   linedata = this.handPH(linedata, 10);
    //   this.allroadPolyline[id_n].setPath(linedata);
    // } else if (this.cllx == "jp") {
    //   if (oneroadPointerarr_now.length > 1) {
    //     // #######纠偏处理
    //     const graspList = this.converTograspList(oneroadPointerarr_now); // 纠偏数据源
    //     const list: any[] = [];
    //     const list_draw: any[] = []; // 纠偏后的
    //     let convert_num: number = Math.ceil(graspList.length / 499);
    //     for (let i = 0; i < convert_num; i++) {
    //       list.push(graspList.slice(i * 499, (i + 1) * 499));
    //     }
    //     list.forEach((arr, index) => {
    //       this.converToTraillist(arr, (list) => {
    //         list_draw[index] = list;
    //         convert_num--;
    //         this.covvertAllok(convert_num, id_n, list_draw);
    //       });
    //     });
    //     // ####### end 纠偏处理
    //   } else {
    //     // 只有长度小于1的数据个数，不能做纠偏
    //     let linedata = oneroadPointerarr_now.map(function (value) {
    //       return [value.jd, value.wd];
    //     });
    //     this.allroadPolyline[id_n].setPath(linedata);
    //   }
    // }


    //############ 处理实时车辆 ###########
    this.allroadMaker[id_n].setPosition(markobj.position);
    this.allroadMaker[id_n].setAngle(Number(markobj.fxj) + 90 + 180); //  0 = 车marker正东方向（顺时针，可以大于360），终端 fxj= 与正北方向顺时针夹角
    this.allroadMaker[id_n].setExtData(markobj);


    // ############信息框的处理###############
    //信息窗口是否关闭，如果是 手动点差关闭的触发close【事件里改为false】，此方法返回false,
    // 如果是执行清除覆盖物的操作，导致信息窗口关闭。此方法返回true
    //防止重复绑定
    if (this.allroadclickcar_clickListener[id_n]) {
      AMap.event.removeListener(this.allroadclickcar_clickListener[id_n]);//移除事件，以绑定时返回的对象作为参数
    }
    this.allroadclickcar_clickListener[id_n] = AMap.event.addListener(this.allroadMaker[id_n], "click", function (e) {
      that.updataWindowMessase(markobj, (resp) => {
        that.mapwin.setContent(resp);
      });//获取新的窗口内容，这个item是即时的

      that.mapwin.open(that.map, markobj.position); //在地图上 显示信息窗口
      that.nowclickcar = markobj;
      that.nowclickcar["flag"] = true;
      that.mapwin.on('close', function () {
        that.nowclickcar["flag"] = false;
      });
    });
    // this.allroadMaker[id_n].on("click", function () {
    //   that.updataWindowMessase(markobj, (resp) => {
    //     that.mapwin.setContent(resp);
    //   });//获取新的窗口内容，这个item是即时的
    //
    //   that.mapwin.open(that.map, markobj.position); //在地图上 显示信息窗口
    //   that.nowclickcar = markobj;
    //   that.nowclickcar["flag"] = true;
    //   that.mapwin.on('close', function () {
    //     that.nowclickcar["flag"] = false;
    //   });
    // });
    const windowcloseflag = this.mapwin.getIsOpen();
    if (windowcloseflag) {
      that.nowclickcar["flag"] = true;
    }
    if (this.nowclickcar && this.nowclickcar["id_n"] == id_n) {
      if (this.nowclickcar["flag"]) {
        that.updataWindowMessase(markobj, (resp) => {
          this.mapwin.setContent(resp);
        });//更新信息窗口内容，这个 that.nowclickcar不是即时的
        this.mapwin.open(this.map, markobj.position); //显示信息窗口
      }
    }
    // ###########处理地图中心和缩放级别
    // const zoomv = this.map.getZoom();//缩放级别
    // if (this.nowclickcar) {
    //   this.map.setZoomAndCenter(zoomv, this.nowclickcar.position);
    // } else {
    //   // 找最后一条线路的车作为参考调整
    //   const lastponterobj = this.allroadPointer[this.lastroad_id_N][this.allroadPointer[this.lastroad_id_N].length - 1];
    //   if (lastponterobj) {
    //     this.map.setZoomAndCenter(zoomv, [lastponterobj.jd, lastponterobj.wd]);
    //   }
    // }

    //#################
    switch (cxlxv) {
      case "sjysrw": {
        // 任务的，点击详情的时候高亮的时候，以 出发地 目的地 地图围栏  和  点击任务关联的车（如果有） 作为地图中心点
        if (this.caozuoid_n_highter && this.caozuoid_n_highter == id_n) {
          const xq_glcarmarker = this.allroadMaker[id_n];
          if (xq_glcarmarker) {
            this.map.setFitView([this.cfdMarker, this.mddMarker, this.viewpolygon, xq_glcarmarker]);
          } else {
            this.map.setFitView([this.cfdMarker, this.mddMarker, this.viewpolygon]);
          }
        }
        if (this.caozuoid_n_glsbxx && this.caozuoid_n_glsbxx == id_n) {
          this.hander_bqzt('rw', id_n, "reload");
        }
      }
        break;
      case "sczdsb": {
        if (this.caozuoid_n_glsbxx && this.caozuoid_n_glsbxx == id_n) {
          // 终端点击详情的时候
          this.hander_bqzt('zdsb', id_n, "reload");
          this.hander_zdssmsg(id_n, 'reload');
        }
      }
        break;
      case "dzbqsb": {
        if (this.caozuoid_n_glsbxx && this.caozuoid_n_glsbxx == id_n) {
          this.hander_dzbqsbssmsg(id_n, 'reload');
        }
      }
    }
  }

  /**
   * 判断是否转化完毕,仅纠偏
   */
  covvertAllok(convertnum: number, id_n: string, list_draw: any): void {
    const that = this;
    if (convertnum == 0) {
      let linearr: any[] = [];
      list_draw.forEach((item) => {
        linearr = linearr.concat(item);
      });
      // linearr = this.handPH(linearr);
      this.allroadPolyline[id_n].setPath(linearr);
    }
  }

  /**
   *
   * @param nowjd
   * @param nowwd
   * @param mddjd---目的地经度
   * @param mddwd --目的地维度
   * @returns {number}  m
   */
  getGetDisance(nowjd: any, nowwd: any, mddjd: any, mddwd: any): number {
    if ((Math.abs(nowwd) > 90) || (Math.abs(mddwd) > 90)) {
      return 0;
    }
    if ((Math.abs(nowjd) > 180) || (Math.abs(mddjd) > 180)) {
      return 0;
    }
    const g = this.rad(nowwd);
    const h = this.rad(mddwd);
    const a = g - h;
    const b = this.rad(nowjd) - this.rad(mddjd);
    let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(g) * Math.cos(h) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    return parseInt(Number(s * 1000).toFixed(0));  // 正整数
  }

  rad(d: any): number {
    return d * Math.PI / 180.0;
  }

  /**
   * 转换为 grasp 要求的数据格式，后续用来纠正
   * @param lssjlist
   * @returns {any}
   */
  converTograspList(lssjlist: any): any {
    const grasplist: any[] = [];
    lssjlist.forEach((obj, index) => {
      const info: any = {
        x: 0.0,
        y: 0.0,
        sp: 0,
        ag: 0,
        tm: 0
      };
      const jdv = obj.jd;
      const wdv = obj.wd;
      const speedv = obj.sd ? Number(obj.sd) : 0;
      const fxjv = Number(obj.fxj) ? Number(obj.fxj) : 0;
      info.x = parseFloat(jdv);
      info.y = parseFloat(wdv);
      info.sp = parseFloat(speedv.toString());
      info.ag = parseFloat(fxjv.toString()); // ag [0 360]  与正北方向的顺时针夹角

      if (index == 0) {
        const nowms = this.commservice.convertTimeToInt(obj.sj);
        const nowseconds = Math.round(nowms / 1000);
        info.tm = nowseconds;
      } else {
        const nowms = this.commservice.convertTimeToInt(obj.sj);
        const nowseconds = Math.round(nowms / 1000);
        const cjtime = nowseconds - grasplist[0].tm;
        info.tm = cjtime;
      }
      grasplist.push(info);
    });
    this.commservice.warn("converTograspList", "纠偏数据源", grasplist);
    return grasplist;
  }

  /**
   * 道路纠偏
   * @param grasplist
   * @returns {any}
   * 返回路径 [[jd,wd],[jd,wd],....]
   */
  converToTraillist(grasplist: any, callback: Function): void {
    this.graspobj.driving(grasplist, (error, result) => {
      if (!error) {
        const path2 = [];
        const newPath = result.data.points;
        newPath.forEach((item) => {
          path2.push([item.x, item.y]);
        });
        callback(path2);
      } else {
        this.commservice.myswal("warning", "道路纠正错误", "", "ts", null);
      }
    });
  }

  updataWindowMessase(markobj: any, callback: Function): any {
    const markerlx = markobj.markerlx;
    const markerpostion = markobj.position;
    this.getAddresss(markerpostion, (resp) => {
      markobj["dzmc"] = resp.regeocode.formattedAddress;
      const info: any[] = [];
      if (markerlx == "sjysrw") {
        info.push("<div style='padding:0px 0px 0px 4px;'><b>" + markobj.ysrwmc + "</b>");
        info.push("目的地 : " + markobj.mddmc);
        info.push("速度 : " + markobj.sd + "km/h");
        // info.push("角度 : " + markobj.fxj);
        info.push("距离目的地距离 : " + markobj.distantv + "米");
        info.push("地址 : " + markobj.dzmc);
        info.push("</div>");
      } else if (markerlx == "sczdsb") {
        info.push("终端名称 : " + markobj.scdzmc);
        info.push("终端ID : " + markobj.id_n);
        info.push("终端电量 : " + markobj.dl);
        info.push("时间 : " + markobj.sj);
        info.push("地址 : " + markobj.dzmc);
      } else if (markerlx == "dzbqsb") {
        info.push("标签ID : " + markobj.id_n);
        info.push("gnss电量 : " + markobj.gnssdl);
        info.push("蓝牙电量 : " + markobj.lydl);
        info.push("时间 : " + markobj.sj);
        info.push("地址 : " + markobj.dzmc);
      }
      callback(info.join("<br/>"));
    });
  }

  /**
   * 某个实时轨迹点和 客户端时间差值,是否超过特定时间
   * @param {string} sj
   * @returns {boolean}
   */
  getTimerange(sj: string): boolean {
    const now = this.commservice.convertTimeToInt(this.commservice.YMDHMS_get(false));
    const lastsj = this.commservice.convertTimeToInt(sj);
    this.commservice.warn("时间差", "", (now - lastsj));

    this.commservice.log("现在的电脑时间", this.commservice.YMDHMS_get(false));
    this.commservice.log("最后一条数据返回的时间", sj);
    return (now - lastsj) > this.timeRange;
  }

  /**
   * 任务表格
   * @param data
   */
  inittable_rwClient(data: any): void {
    const that = this;
    $("#table_rw table").bootstrapTable('destroy');
    const obj = {
      classes: 'table  table-bordered', //没有 border,默认是 table table-hover
      locale: 'zh-CN',
      virtualScroll: true,
      sidePagination: "client", //分页方式：client 客户端分页，server 服务端分页（*）
      pageSize: 20, //每页的个数
      pageNumber: 1, //默认是1
      pageList: [20, 30],
      pagination: true, //是否显示分页（*）  默认false
      paginationHAlign: 'right', //right, left
      paginationVAlign: 'bottom', //bottom, top, both
      paginationDetailHAlign: 'left', //right, left
      data: data,
      columns: [{
        title: '运送任务名称',
        field: 'ysrwmc',
        cellStyle: function () {
          return {
            classes: 'td1'
          }
        },
      }, {
        title: '操作',
        field: 'caozuo',
        width: 140,
        cellStyle: function () {
          return {
            classes: 'td2'
          }
        },
        events: that.myevents,
        formatter: function (v) {
          let str: string = "";
          if (!v) {
            str += "<button type='button' class='btn btn-xs btn-info info_rw'><i class='fa fa-search'></i> 详情</button>";
          } else {
            str += "<button type='button' class='btn btn-xs btn-info info_rw'><i class='fa fa-search'></i> 详情</button>";
            str += "<button type='button' class='btn btn-xs btn-danger cancel_glrw'> 取消高亮</button>";
          }
          return str;
        }
      }]
    };
    const ajustheight = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 220;
    if (this.sysBase == "61") {
      obj.pageSize = 50;
      obj.pageList = [50];
      obj["hiddenPageinfoLink"] = true;
      obj["paginationLoop"] = true;
      obj["paginationPreText"] = "<i class='fa fa-arrow-left'></i>上一页";
      obj["paginationNextText"] = "下一页<i class='fa fa-arrow-right'></i>";
      obj["height"] = ajustheight;
    } else {
      obj.pageSize = 50;
      obj.pageList = [50];
      obj["hiddenPageinfoLink"] = true;
      obj["paginationLoop"] = true;
      obj["paginationPreText"] = "<i class='fa fa-arrow-left'></i>上一页";
      obj["paginationNextText"] = "下一页<i class='fa fa-arrow-right'></i>";
      obj["height"] = ajustheight;
    }
    $("#table_rw table").bootstrapTable(obj);
    setTimeout(() => {
      $("#table_rw table").bootstrapTable("resetView", ajustheight);
    }, 100)
  }

  /**
   * 终端表格
   * @param data
   */
  inittable_zdsbClient(data: any): void {
    const that = this;
    $("#table_zdsb table").bootstrapTable('destroy');
    const obj = {
      classes: 'table  table-bordered', //没有 border,默认是 table table-hover
      locale: 'zh-CN',
      sidePagination: "client", //分页方式：client 客户端分页，server 服务端分页（*）
      pageSize: 20, //每页的个数
      pageNumber: 1, //默认是1
      pageList: [20, 30],
      pagination: true, //是否显示分页（*）  默认false
      paginationHAlign: 'right', //right, left
      paginationVAlign: 'bottom', //bottom, top, both
      paginationDetailHAlign: 'left', //right, left
      data: data,
      columns: [{
        title: '终端名称',
        field: 'scdzmc',
        cellStyle: function () {
          return {
            classes: 'td1'
          }
        },
      }, {
        title: '操作',
        field: 'caozuo',
        width: 250,
        cellStyle: function () {
          return {
            classes: 'td2'
          }
        },
        events: that.myevents,
        formatter: function (v) {
          let str: string = "";
          if (!v) {
            str += "<button type='button' class='btn btn-xs btn-info info_zdsb'><i class='fa fa-search'></i> 详情</button>";
            str += "<button type='button' class='btn btn-xs btn-info sendmsg_zdsb'><i class='fa fa-pencil-square-o'></i> 发消息</button>";
          } else {
            str += "<button type='button' class='btn btn-xs btn-info info_zdsb'><i class='fa fa-search'></i> 详情</button>";
            str += "<button type='button' class='btn btn-xs btn-info sendmsg_zdsb'><i class='fa fa-pencil-square-o'></i> 发消息</button>";
            str += "<button type='button' class='btn btn-xs btn-danger cancel_glzdsb'> 取消高亮</button>";
          }
          return str;
        }
      }]
    };
    const ajustheight = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 220;
    if (this.sysBase == "61") {
      obj.pageSize = 50;
      obj.pageList = [50];
      obj["hiddenPageinfoLink"] = true;
      obj["paginationLoop"] = true;
      obj["paginationPreText"] = "<i class='fa fa-arrow-left'></i>上一页";
      obj["paginationNextText"] = "下一页<i class='fa fa-arrow-right'></i>";
      obj["height"] = ajustheight;
    } else {
      obj.pageSize = 50;
      obj.pageList = [50];
      obj["hiddenPageinfoLink"] = true;
      obj["paginationLoop"] = true;
      obj["paginationPreText"] = "<i class='fa fa-arrow-left'></i>上一页";
      obj["paginationNextText"] = "下一页<i class='fa fa-arrow-right'></i>";
      obj["height"] = ajustheight;
    }
    $("#table_zdsb table").bootstrapTable(obj);
    setTimeout(() => {
      $("#table_zdsb table").bootstrapTable("resetView", ajustheight);
    }, 100)
  }

  /**
   * 电子标签表格
   * @param data
   */
  inittable_bqsbClient(data: any): void {
    const that = this;
    $("#table_dzbqsb table").bootstrapTable('destroy');
    const obj = {
      classes: 'table  table-bordered', //没有 border,默认是 table table-hover
      locale: 'zh-CN',
      sidePagination: "client", //分页方式：client 客户端分页，server 服务端分页（*）
      pageSize: 20, //每页的个数
      pageNumber: 1, //默认是1
      pageList: [20, 30],
      pagination: true, //是否显示分页（*）  默认false
      paginationHAlign: 'right', //right, left
      paginationVAlign: 'bottom', //bottom, top, both
      paginationDetailHAlign: 'left', //right, left
      data: data,
      columns: [{
        title: '标签ID',
        field: 'id',
        cellStyle: function () {
          return {
            classes: 'td1'
          }
        },
      }, {
        title: "试卷包名称",
        field: 'bqglsjxxList',
        cellStyle: function () {
          return {
            classes: 'td2'
          }
        },
        formatter: function (v, row) {
          let retstr: string = "";
          if (v && v.length) {
            // const kmlist = v.map((item) => {
            //   return item.kmmc;
            // });
            // retstr = that.commservice.showTenchart(kmlist.join(";"), 10);
            retstr = row.sjbmc;
          } else {
            retstr = "<span class='text-danger'>未绑定试卷包</span>";
          }
          return retstr;
        }
      }, {
        title: '操作',
        field: 'caozuo',
        width: 140,
        cellStyle: function () {
          return {
            classes: 'td2'
          }
        },
        events: that.myevents,
        formatter: function (v) {
          let str: string = "";
          if (!v) {
            str += "<button type='button' class='btn btn-xs btn-info info_dzbqsb'><i class='fa fa-search'></i> 详情</button>";
          } else {
            str += "<button type='button' class='btn btn-xs btn-info info_dzbqsb'><i class='fa fa-search'></i> 详情</button>";
            str += "<button type='button' class='btn btn-xs btn-danger cancel_glbqsb'> 取消高亮</button>";
          }
          return str;
        }
      }]
    };
    const ajustheight = this.commservice.getViewPort().height - this.commservice.topH - this.commservice.topmenuH - 220;
    if (this.sysBase == "61") {
      obj.pageSize = 50;
      obj.pageList = [50];
      obj["hiddenPageinfoLink"] = true;
      obj["paginationLoop"] = true;
      obj["paginationPreText"] = "<i class='fa fa-arrow-left'></i>上一页";
      obj["paginationNextText"] = "下一页<i class='fa fa-arrow-right'></i>";
      obj["height"] = ajustheight;
    } else {
      obj.pageSize = 50;
      obj.pageList = [50];
      obj["hiddenPageinfoLink"] = true;
      obj["paginationLoop"] = true;
      obj["paginationPreText"] = "<i class='fa fa-arrow-left'></i>上一页";
      obj["paginationNextText"] = "下一页<i class='fa fa-arrow-right'></i>";
      obj["height"] = ajustheight;
    }

    $("#table_dzbqsb table").bootstrapTable(obj);
    setTimeout(() => {
      $("#table_dzbqsb table").bootstrapTable("resetView", ajustheight);
    }, 100)
  }

  @HostListener("window:myevents", ["$event"])
  myevents = {
    "click .info_rw": function (e, value, row, index) {
      this.actionhander_rwinfo(row, index);
    }.bind(this),
    "click .cancel_glrw": function (e, value, row, index) {
      //取消高亮
      const ysrwbhv = row.ysrwbh;
      if (this.caozuoid_n_highter) {
        if (this.allroadMaker[this.caozuoid_n_highter]) {
          const marker = this.allroadMaker[this.caozuoid_n_highter].getExtData();
          const flag = this.getTimerange(marker.sj);
          // 还原 轨迹颜色
          let initpolylineColor: string = "";
          if (flag) {
            initpolylineColor = this.polylineColor["gs"];
          } else {
            initpolylineColor = this.polylineColor['sjysrw'];  // 各自查询类型定义的颜色
          }
          this.allroadPolyline[this.caozuoid_n_highter].setOptions({
            strokeColor: initpolylineColor,
            zIndex: 50
          });
          // 还原图标
          let iconurl: string = "";
          if (flag) {
            iconurl = this.carImage['rw4'];
          } else {
            if (Number(marker["sd"])) {
              iconurl = this.carImage['rw2'];
            } else {
              iconurl = this.carImage["rw3"];
            }
          }
          this.allroadMaker[ysrwbhv].setIcon(new AMap.Icon({
            image: iconurl,
            imageOffset: new AMap.Pixel(0, 0),
            imageSize: new AMap.Size(34, 18)
          }));
          this.allroadMaker[ysrwbhv].setzIndex(100);
        }
      }
      $("#table_rw table").bootstrapTable("updateCell", {index: index, field: "caozuo", value: ""});
      this.caozuoid_n_highter = "";

    }.bind(this),
    "click .info_zdsb": function (e, value, row, index) {
      this.actionhander_zdsbinfo(row, index);
    }.bind(this),
    "click .cancel_glzdsb": function (e, value, row, index) {
      //取消高亮
      const id = row.id;
      if (this.caozuoid_n_highter) {
        if (this.allroadMaker[this.caozuoid_n_highter]) {
          const marker = this.allroadMaker[this.caozuoid_n_highter].getExtData();
          const flag = this.getTimerange(marker.sj);
          // 还原 轨迹颜色
          let initpolylineColor: string = "";
          if (flag) {
            initpolylineColor = this.polylineColor["gs"];
          } else {
            initpolylineColor = this.polylineColor['sczdsb'];  // 各自查询类型定义的颜色
          }
          this.allroadPolyline[this.caozuoid_n_highter].setOptions({
            strokeColor: initpolylineColor,
            zIndex: 50
          });
          // 还原图标
          let iconurl: string = "";
          if (flag) {
            iconurl = this.carImage['zdsb4'];
          } else {
            if (Number(marker["sd"])) {
              iconurl = this.carImage['zdsb2'];
            } else {
              iconurl = this.carImage["zdsb3"];
            }
          }
          this.allroadMaker[id].setIcon(new AMap.Icon({
            image: iconurl,
            imageOffset: new AMap.Pixel(0, 0),
            imageSize: new AMap.Size(34, 18)
          }));
          this.allroadMaker[id].setzIndex(100);
        }
      }
      $("#table_zdsb table").bootstrapTable("updateCell", {index: index, field: "caozuo", value: ""});
      this.caozuoid_n_highter = "";
    }.bind(this),
    "click .sendmsg_zdsb": function (e, value, row, index) {
      this.caozuoid_n = row.id;
      this.formgroup_zdsbmsg.reset();
      $("#send_msgModal").modal({
        keyboard: true,
        backdrop: "static"
      });
    }.bind(this),
    "click .info_dzbqsb": function (e, value, row, index) {
      this.actionhander_dzbqsbinfo(row, index);
    }.bind(this),
    "click .cancel_glbqsb": function (e, value, row, index) {
      //取消高亮
      const id = row.id;
      if (this.caozuoid_n_highter) {
        if (this.allroadMaker[this.caozuoid_n_highter]) {
          const marker = this.allroadMaker[this.caozuoid_n_highter].getExtData();
          const flag = this.getTimerange(marker.sj);
          // 还原 轨迹颜色
          let initpolylineColor: string = "";
          if (flag) {
            initpolylineColor = this.polylineColor["gs"];
          } else {
            initpolylineColor = this.polylineColor['dzbqsb'];  // 各自查询类型定义的颜色
          }
          this.allroadPolyline[this.caozuoid_n_highter].setOptions({
            strokeColor: initpolylineColor,
            zIndex: 50
          });
          // 还原图标
          let iconurl: string = "";
          if (flag) {
            iconurl = this.carImage['bqsb4'];
          } else {
            if (Number(marker["sd"])) {
              iconurl = this.carImage['bqsb2'];
            } else {
              iconurl = this.carImage["bqsb3"];
            }
          }
          this.allroadMaker[id].setIcon(new AMap.Icon({
            image: iconurl,
            imageOffset: new AMap.Pixel(0, 0),
            imageSize: new AMap.Size(34, 18)
          }));
          this.allroadMaker[id].setzIndex(100);
        }
      }
      $("#table_dzbqsb table").bootstrapTable("updateCell", {index: index, field: "caozuo", value: ""});
      this.caozuoid_n_highter = "";
    }.bind(this),

  }

  /**
   * 任务表格中的  详情
   * 1： 高亮处理
   * 2：地图中心，出发地，目的地，地图围栏，点的这个任务对应的图标
   * 3： 点的这个任务对应的图标和轨迹线要高亮显示
   * 4： 弹框显示 关联的试卷信息
   * @param row
   */
  actionhander_rwinfo(row: any, rowindex: number): void {
    const ysrwbhv = row.ysrwbh;
    //########## 还原操作 ###################
    // 取消上次点击的 图标 和  轨迹的高亮颜色, 恢复至他点击前的轨迹颜色和图标
    if (this.caozuoid_n_highter) {
      if (this.allroadMaker[this.caozuoid_n_highter]) {
        const marker = this.allroadMaker[this.caozuoid_n_highter].getExtData();
        const flag = this.getTimerange(marker.sj);
        // 还原 轨迹颜色
        let initpolylineColor: string = "";
        if (flag) {
          initpolylineColor = this.polylineColor["gs"];
        } else {
          initpolylineColor = this.polylineColor['sjysrw'];  // 各自查询类型定义的颜色
        }
        this.allroadPolyline[this.caozuoid_n_highter].setOptions({
          strokeColor: initpolylineColor,
          zIndex: 50
        });
        // 还原图标
        let iconurl: string = "";
        if (flag) {
          iconurl = this.carImage['rw4'];
        } else {
          if (Number(marker["sd"])) {
            iconurl = this.carImage['rw2'];
          } else {
            iconurl = this.carImage["rw3"];
          }
        }
        this.allroadMaker[this.caozuoid_n_highter].setIcon(new AMap.Icon({
          image: iconurl,
          imageOffset: new AMap.Pixel(0, 0),
          imageSize: new AMap.Size(34, 18)
        }));
        this.allroadMaker[this.caozuoid_n_highter].setzIndex(100);
      }
    }
    //隐藏全部的高亮
    const alldata = $("#table_rw table").bootstrapTable("getData"); //客户端分页获取所有的
    alldata.forEach((item, index2) => {
      $("#table_rw table").bootstrapTable("updateCell", {index: index2, field: "caozuo", value: ""});
    })
    // 显示取消高亮的按钮
    $("#table_rw table").bootstrapTable("updateCell", {index: rowindex, field: "caozuo", value: "cancelgl"});

    //###############设置操作 #######
    this.caozuoid_n_highter = ysrwbhv; // 实时处理标识
    if (this.allroadPolyline[ysrwbhv]) {
      this.allroadPolyline[ysrwbhv].setOptions({
        strokeColor: this.polylineColor["highter"],
        zIndex: 55
      });
    }
    if (this.allroadMaker[ysrwbhv]) {
      this.allroadMaker[ysrwbhv].setIcon(new AMap.Icon({
        image: this.carImage["rw5"],
        imageOffset: new AMap.Pixel(0, 0),
        imageSize: new AMap.Size(34, 18)
      }));
      this.allroadMaker[ysrwbhv].setzIndex(105);
    }

    //#########高亮的时候， 以出发地 目的地 地图围栏 高亮车作为地图中心点 ##############
    this.cfdMarker.hide();
    this.mddMarker.hide();
    this.viewpolygon.hide();
    const cfdmc = row.cfdmc;
    const mddmc = row.mddmc;
    const cfdposition = [row.cfdjd, row.cfdwd];
    const mddposition = [row.mddjd, row.mddwd];
    if (cfdposition.length && mddposition.length) {
      this.setPositionDZ(cfdmc, cfdposition, mddmc, mddposition);
    }
    const dtwlstr = row.dtwl;
    if (dtwlstr) {
      try {
        const wlarr = JSON.parse(dtwlstr);
        this.viewpolygon.show();
        this.viewpolygon.setPath(wlarr);
      } catch (e) {

      }
    }
    // this.map.setFitView();
    const fgwcenter: any[] = [this.cfdMarker, this.mddMarker, this.viewpolygon];
    if (this.allroadMaker[ysrwbhv]) {
      fgwcenter.push(this.allroadMaker[ysrwbhv]);
    }
    this.map.setFitView(fgwcenter);
    // #########################任务关联的标签是固定的，  终端扫描到的在实时轨迹中返回，做比对，并获得试卷包里的信息###########
    this.caozuoid_n_glsbxx = ysrwbhv; // 实时处理标识
    const rwbhdzbqidListv = row.rwbhdzbqidList ? row.rwbhdzbqidList : [];
    if (!rwbhdzbqidListv.length) {
      this.commservice.myswal("warning", "任务未关联标签", "", "ts", null);
      return
    }
    // 切换任务的时候先清空显示
    this.rw_glbqList.length = 0;
    this.rw_glbqListbase = rwbhdzbqidListv; // 标签id 固定
    this.hander_bqzt('rw', ysrwbhv, "init");// 处理标签的登记状态
    $(".rw_glsjxx").show();
    // $('.rw_glsjxx>.body').slimScroll({
    //   height: 370,
    //   alwaysVisible: true,
    //   color: "#0050C3",
    //   railColor: "#3598DC",
    //   railVisible: true,
    //   railOpacity: .8
    // });
  }


  /**
   * 终端设备表格的  详情
   *1  高亮处理
   * 2:  终端扫描的标签显示，只显示实时的
   * @param row
   */
  actionhander_zdsbinfo(row: any, rowindex: number): void {
    const zdsbid = row.id;
    //########## 还原操作 ##########
    // 取消上次点击的 图标 和  轨迹的高亮颜色, 恢复至他点击前的轨迹颜色和图标
    if (this.caozuoid_n_highter) {
      if (this.allroadMaker[this.caozuoid_n_highter]) {
        const marker = this.allroadMaker[this.caozuoid_n_highter].getExtData();
        const flag = this.getTimerange(marker.sj);
        // 还原 轨迹颜色
        let initpolylineColor: string = "";
        if (flag) {
          initpolylineColor = this.polylineColor["gs"];
        } else {
          initpolylineColor = this.polylineColor['sczdsb'];  // 各自查询类型定义的颜色
        }
        this.allroadPolyline[this.caozuoid_n_highter].setOptions({
          strokeColor: initpolylineColor,
          zIndex: 50
        });
        // 还原图标
        let iconurl: string = "";
        if (flag) {
          iconurl = this.carImage['zdsb4'];
        } else {
          if (Number(marker["sd"])) {
            iconurl = this.carImage['zdsb2'];
          } else {
            iconurl = this.carImage["zdsb3"];
          }
        }
        this.allroadMaker[this.caozuoid_n_highter].setIcon(new AMap.Icon({
          image: iconurl,
          imageOffset: new AMap.Pixel(0, 0),
          imageSize: new AMap.Size(34, 18)
        }));
        this.allroadMaker[this.caozuoid_n_highter].setzIndex(100);
      }
    }

    const alldata = $("#table_zdsb table").bootstrapTable("getData"); //客户端分页获取所有的
    alldata.forEach((item, index2) => {
      $("#table_zdsb table").bootstrapTable("updateCell", {index: index2, field: "caozuo", value: ""});
    })
    // 显示取消高亮的按钮
    $("#table_zdsb table").bootstrapTable("updateCell", {index: rowindex, field: "caozuo", value: "cancelgl"});
    //############ 设置操作 ##########
    this.caozuoid_n_highter = zdsbid; // 实时处理标识
    if (this.allroadPolyline[zdsbid]) {
      this.allroadPolyline[zdsbid].setOptions({
        strokeColor: this.polylineColor["highter"],
        zIndex: 55
      });
    }
    if (this.allroadMaker[zdsbid]) {
      this.allroadMaker[zdsbid].setIcon(new AMap.Icon({
        image: this.carImage["zdsb5"],
        imageOffset: new AMap.Pixel(0, 0),
        imageSize: new AMap.Size(34, 18)
      }));
      this.allroadMaker[zdsbid].setzIndex(105);
    }
    //#################### 处理 终端标签 ####################
    this.caozuoid_n_glsbxx = zdsbid; // 实时标识
    this.zdsb_glbqList.length = 0;
    this.hander_bqzt('zdsb', zdsbid, "init");
    $(".zdsb_glsjxx").show();
    // $('.zdsb_glsjxx .has').slimScroll({
    //   height: 250,
    //   alwaysVisible: true,
    //   color: "#0050C3",
    //   railColor: "#3598DC",
    //   railVisible: true,
    //   railOpacity: .8
    // });
    // 点击终端的实时信息
    this.zdsb_ssmsg.scdzmc = "";
    this.zdsb_ssmsg.id = "";
    this.zdsb_ssmsg.dl = "";
    this.zdsb_ssmsg.sj = "";
    this.zdsb_ssmsg.dzmc = "";
    this.hander_zdssmsg(zdsbid, 'init');
  }

  /**
   * 电子标签表格的详情按钮
   * 点的这个标签设备对应的图标和轨迹线要高亮显示,
   *
   * @param row
   */
  actionhander_dzbqsbinfo(row: any, rowindex: number): void {
    const bqsbid = row.id;
    //########### 还原操作  表格+ 地图 ###############
    // 取消上次点击的 图标 和  轨迹的高亮颜色, 恢复至他点击前的轨迹颜色和图标
    if (this.caozuoid_n_highter) {
      if (this.allroadMaker[this.caozuoid_n_highter]) {
        const marker = this.allroadMaker[this.caozuoid_n_highter].getExtData();
        const flag = this.getTimerange(marker.sj);
        // 还原 轨迹颜色
        let initpolylineColor: string = "";
        if (flag) {
          initpolylineColor = this.polylineColor["gs"];
        } else {
          initpolylineColor = this.polylineColor['dzbqsb'];  // 各自查询类型定义的颜色
        }
        this.allroadPolyline[this.caozuoid_n_highter].setOptions({
          strokeColor: initpolylineColor,
          zIndex: 50
        });
        // 还原图标
        let iconurl: string = "";
        if (flag) {
          iconurl = this.carImage['bqsb4'];
        } else {
          if (Number(marker["sd"])) {
            iconurl = this.carImage['bqsb2'];
          } else {
            iconurl = this.carImage["bqsb3"];
          }
        }
        this.allroadMaker[this.caozuoid_n_highter].setIcon(new AMap.Icon({
          image: iconurl,
          imageOffset: new AMap.Pixel(0, 0),
          imageSize: new AMap.Size(34, 18)
        }));
        this.allroadMaker[this.caozuoid_n_highter].setzIndex(100);
      }
    }
    //隐藏全部【取消高亮】的按钮
    const alldata = $("#table_dzbqsb table").bootstrapTable("getData"); //客户端分页获取所有的
    alldata.forEach((item, index2) => {
      $("#table_dzbqsb table").bootstrapTable("updateCell", {index: index2, field: "caozuo", value: ""});
    })
    // 显示单击这条的 【取消高亮】的按钮
    $("#table_dzbqsb table").bootstrapTable("updateCell", {index: rowindex, field: "caozuo", value: "cancelgl"});

    //#################设置当前点击的操作 ##############
    this.caozuoid_n_highter = bqsbid;  //实时处理标识
    if (this.allroadPolyline[bqsbid]) {
      this.allroadPolyline[bqsbid].setOptions({
        strokeColor: this.polylineColor["highter"],
        zIndex: 55
      });
    }
    if (this.allroadMaker[bqsbid]) {
      this.allroadMaker[bqsbid].setIcon(new AMap.Icon({
        image: this.carImage["bqsb5"],
        imageOffset: new AMap.Pixel(0, 0),
        imageSize: new AMap.Size(34, 18)
      }));
      this.allroadMaker[bqsbid].setzIndex(105);
    }

    // #######################   试卷 包信息 #########
    this.caozuoid_n_glsbxx = bqsbid;  // 实时处理标识
    this.dzbqsb_glbqselfList.length = 0;
    const bqglsjxxListv = row.bqglsjxxList; // 标签关联的试卷包
    this.dzbqsb_glbqselfList.push({
      bqid: bqsbid,
      sjbmc: row.sjbmc,
      sjbglzt: (bqglsjxxListv && bqglsjxxListv.length) ? true : false,
      sjbgllist: bqglsjxxListv
    });
    // 标签实时信息
    $(".dzbqsb_xx").show();
    this.dzbqsb_ssmsg.id = "";
    this.dzbqsb_ssmsg.gnssdl = "";
    this.dzbqsb_ssmsg.lydl = "";
    this.dzbqsb_ssmsg.sj = "";
    this.dzbqsb_ssmsg.dzmc = "";
    this.hander_dzbqsbssmsg(bqsbid, 'init');
  }


  /**
   *  处理标签的登记状态
   * @param {string} cxlx
   * @param {string} id_n
   * @param {string} flag
   * init--
   * reload-
   */
  hander_bqzt(cxlx: string, id_n: string, flag: string): void {
    switch (cxlx) {
      case "rw": {
        // this.allroadglbqList_cache[id_n] 最新实时的上报标签
        //  this.rw_glbqListbase  任务关联的上报标签id， 固定的
        // 处理 生成   this.rw_glbqList  ----双向绑定页面显示的
        // 更新 rw_glbqList  中的试卷信息
        if (flag == "init") {
          const allbqidlist = this.rw_glbqListbase.concat(this.allroadglbqList_cache[id_n] ? this.allroadglbqList_cache[id_n] : []);
          const allbqidlist_norepeat = this.commservice.fliterRepeat(allbqidlist);
          this.rw_glbqList = allbqidlist_norepeat.map((bqid) => {
            return {
              bqid: bqid,
              bqdjzt: 'wdj',  //标签登记状态， wdj--未登记（灰色） ydj--已登记（绿色） ddj-上报的不在任务里（红色）
              sjbmc: "", //试卷包名称
              sjbglkm: "", // 标签关联的试卷包的科目列表
              sjbglzt: false, // 标签关联试卷包状态
              sjbgllist: []  // 标签关联的试卷包信息
            }
          });
          //######## 更新标签状态 ###########
          this.rw_glbqList.forEach((item) => {
            const bqidv = item.bqid;
            if (this.rw_glbqListbase.indexOf(bqidv) != -1) {
              //  未登记 或者  已经登记的
              if (this.allroadglbqList_cache[id_n] && this.allroadglbqList_cache[id_n].length) {
                if (this.allroadglbqList_cache[id_n].indexOf(bqidv) != -1) {
                  // 已经登记的
                  item.bqdjzt = "ydj";
                } else {
                  item.bqdjzt = "wdj";
                }
              } else {
                item.bqdjzt = "wdj";
              }
            } else {
              // 上报的不在任务里的
              item.bqdjzt = "ddj";
            }
          });
          //#############更新标签关联度的试卷信息  和  试卷状态 #############
          this.hander_bqglsjb(allbqidlist_norepeat, 'rw');
        } else if (flag == "reload") {
          const pre_rw_glbqList = this.rw_glbqList;
          const pre_rw_glbqidList = pre_rw_glbqList.map((item) => {
            return item.bqid;
          });
          const allbqidlist = this.rw_glbqListbase.concat(this.allroadglbqList_cache[id_n] ? this.allroadglbqList_cache[id_n] : []);
          const allbqidlist_norepeat = this.commservice.fliterRepeat(allbqidlist);
          this.rw_glbqList = allbqidlist_norepeat.map((bqid) => {
            if (pre_rw_glbqidList.indexOf(bqid) != -1) {
              //上次已经有数据了
              return pre_rw_glbqList[pre_rw_glbqidList.indexOf(bqid)];  // 标签状态要更新下，试卷包信息不需要更新（标签关联的试卷是固定的）
            } else {
              return {
                bqid: bqid,
                bqdjzt: 'wdj',  //标签登记状态， wdj--未登记（灰色） ydj--已登记（绿色） ddj-上报的不在任务里（红色）
                sjbmc: "", //试卷包名称
                sjbglkm: "", // 标签关联的试卷包的科目列表
                sjbglzt: false, // 标签关联试卷包状态
                sjbgllist: []  // 标签关联的试卷包信息
              }
            }
          });
          //########### 更新 标签的状态
          this.rw_glbqList.forEach((item) => {
            const bqidv = item.bqid;
            if (this.rw_glbqListbase.indexOf(bqidv) != -1) {
              //  未登记 或者  已经登记的
              if (this.allroadglbqList_cache[id_n] && this.allroadglbqList_cache[id_n].length) {
                if (this.allroadglbqList_cache[id_n].indexOf(bqidv) != -1) {
                  // 已经登记的
                  item.bqdjzt = "ydj";
                } else {
                  item.bqdjzt = "wdj";
                }
              } else {
                item.bqdjzt = "wdj";
              }
            } else {
              // 上报的不在任务里的
              item.bqdjzt = "ddj";
            }
          });
          // ###############,更新标签关联度的试卷信息和试卷状态 （ 只需要请求没请求过的  ）
          const bqidlist = [];
          this.allroadglbqList_cache[id_n].forEach((bqid) => {
            if (pre_rw_glbqidList.indexOf(bqid) == -1) {
              bqidlist.push(bqid);
            }
          });
          this.hander_bqglsjb(bqidlist, 'rw');
        }
      }
        break;
      case "zdsb": {
        // 点击了详情，才会开启
        // 只需要显示最新的标签信息就可以。不用和上次的比较
        if (flag == "init") {
          // 第一次点击，需要对缓存做个延迟判断
          if (!this.allroadglbqList_cache[id_n].length) {
            //点的比较快，第一次的实时数据还没回来
            this.commservice.blockUI({
              target: ".body_zdsjxx",
              boxed: true,
              message: "数据获取中...",
              zIndex: 10051,
              overlayColor: "#67809F"
            });
            setTimeout(() => {
              this.commservice.unblockUI(".body_zdsjxx");
              // 延迟10m 后再判断，
              if (!this.allroadglbqList_cache[id_n].length) {
                // 还是没有
                this.zdsb_glbqList.length = 0;
              } else {
                this.zdsb_glbqList = this.allroadglbqList_cache[id_n].map((bqid) => {
                  return {
                    bqid: bqid,
                    sjbmc: "", //试卷包名称
                    sjbglkm: "", // 标签关联的试卷包的科目列表
                    sjbglzt: false, // 标签关联试卷包状态
                    sjbgllist: []  // 标签关联的试卷包信息
                  }
                });
                //########## 处理终端实时扫描到的标签关联试卷包信息和状态
                this.hander_bqglsjb(this.allroadglbqList_cache[id_n], 'zdsb');

              }
            }, 10000);
          } else {
            this.hander_bqzt(cxlx, id_n, 'reload');
          }
        } else if (flag == "reload") {
          const pre_zdsb_glbqList = this.zdsb_glbqList;
          //console.log(pre_zdsb_glbqList);
          const pre_zdsb_glbqidList = pre_zdsb_glbqList.map((item) => {
            return item.bqid;
          });

          // 这一次实时轨迹中有多少个显示多少个
          this.zdsb_glbqList = this.allroadglbqList_cache[id_n].map((bqid) => {
            if (pre_zdsb_glbqidList.indexOf(bqid) != -1) {
              return pre_zdsb_glbqList[pre_zdsb_glbqidList.indexOf(bqid)];
            } else {
              return {
                bqid: bqid,
                sjbmc: "", //试卷包名称
                sjbglkm: "", // 标签关联的试卷包的科目列表
                sjbglzt: false, // 标签关联试卷包状态
                sjbgllist: []  // 标签关联的试卷包信息
              }
            }
          });
          //########## 处理终端实时扫描到的标签关联试卷包信息和状态只要请求(本次标签中，上次数据中未请求的)
          const bqidlist = [];
          this.allroadglbqList_cache[id_n].forEach((bqid) => {
            if (pre_zdsb_glbqidList.indexOf(bqid) == -1) {
              bqidlist.push(bqid);
            }
          });
          this.hander_bqglsjb(bqidlist, 'zdsb');
        }
      }
        break;
    }

  }

  /**
   *  标签关联试卷的数据
   * @param bqidlist  任务关联的 标签id集合
   */
  hander_bqglsjb(bqidlist: any, cxlx: string): void {
    if (!bqidlist.length) {
      return;
    }
    const url = "sjgz/gjcx/cxbqglsjxx";
    this.itservice.kwPtPost(url, {
      dzbqidList: bqidlist,
      ksjhbh: this.s_obj.ksjhbh
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const dzbqGlSjxxListv = resp.dzbqGlSjxxList;
            if (dzbqGlSjxxListv && dzbqGlSjxxListv.length) {
              switch (cxlx) {
                case "rw": {
                  this.rw_glbqList.forEach((item) => {
                    const bqid = item.bqid;
                    dzbqGlSjxxListv.forEach((sjxx) => {
                      if (bqid == sjxx.dzbqid) {
                        item.sjbmc = sjxx.sjbmc;
                        const glSjxxListv = sjxx.glSjxxList ? sjxx.glSjxxList : [];
                        if (glSjxxListv.length) {
                          item.sjbglzt = true;
                        } else {
                          item.sjbglzt = false;
                        }
                        item.sjbgllist = glSjxxListv;
                        const glSjxxList_kmList = glSjxxListv.map((item) => {
                          return item.kmmc;
                        });
                        item.sjbglkm = this.commservice.showTenchart(glSjxxList_kmList.join(";"), 8);
                      }
                    });
                  });
                }
                  break;
                case "zdsb": {
                  this.zdsb_glbqList.forEach((item) => {
                    const bqid = item.bqid;
                    dzbqGlSjxxListv.forEach((sjxx) => {
                      if (bqid == sjxx.dzbqid) {
                        item.sjbmc = sjxx.sjbmc;
                        const glSjxxListv = sjxx.glSjxxList ? sjxx.glSjxxList : [];
                        if (glSjxxListv.length) {
                          item.sjbglzt = true;
                        } else {
                          item.sjbglzt = false;
                        }
                        item.sjbgllist = glSjxxListv;
                        const glSjxxList_kmList = glSjxxListv.map((item) => {
                          return item.kmmc;
                        });
                        item.sjbglkm = this.commservice.showTenchart(glSjxxList_kmList.join(";"), 8);
                      }
                    });
                  });
                }
                  break;
              }
            }
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
          }
        } else {
          this.hander_bqglsjb(bqidlist, cxlx);
        }
      });
    });
  }


  /**
   * 处理点击的终端详情  实时位置信息
   * @param {string} zdsbid
   * @param {string} flag
   */
  hander_zdssmsg(zdsbid: string, flag: string): void {
    if (flag == "init") {
      if (!this.allroadMaker[zdsbid]) {
        //刚进来就点击详情，第一次实时数据还没获取到
        this.commservice.blockUI({
          target: ".body_zdssxx",
          boxed: true,
          message: "数据获取中...",
          zIndex: 10051,
          overlayColor: "#67809F"
        });
        setTimeout(() => {
          this.commservice.unblockUI(".body_zdssxx");
          if (!this.allroadMaker[zdsbid]) {
            //是真的没有数据
          } else {
            const markobj = this.allroadMaker[zdsbid].getExtData(); // 里面没有位置信息
            this.zdsb_ssmsg.scdzmc = this.commservice.removeSpace(false, markobj.scdzmc);
            this.zdsb_ssmsg.id = this.commservice.removeSpace(false, markobj.id_n);
            this.zdsb_ssmsg.dl = this.commservice.removeSpace(false, markobj.dl);
            this.zdsb_ssmsg.sj = this.commservice.removeSpace(false, markobj.sj);
            this.getAddresss(markobj.position, (resp) => {
              this.zdsb_ssmsg.dzmc = resp.regeocode.formattedAddress;
            });
          }
        }, 10000);
      } else {
        this.hander_zdssmsg(zdsbid, 'reload');
      }
    } else {
      const markobj = this.allroadMaker[zdsbid].getExtData(); // 里面没有位置信息
      this.zdsb_ssmsg.scdzmc = markobj.scdzmc;
      this.zdsb_ssmsg.id = markobj.id_n;
      this.zdsb_ssmsg.dl = markobj.dl;
      this.zdsb_ssmsg.sj = markobj.sj;
      this.getAddresss(markobj.position, (resp) => {
        this.zdsb_ssmsg.dzmc = resp.regeocode.formattedAddress;
      });
    }
  }

  /**
   * 处理点击的标签设备  实时位置信息
   * @param {string} bqsbid
   * @param {string} flag
   */
  hander_dzbqsbssmsg(bqsbid: string, flag: string): void {
    if (flag == "init") {
      if (!this.allroadMaker[bqsbid]) {
        //刚进来就点击详情，第一次实时数据还没获取到
        this.commservice.blockUI({
          target: ".body_bqssxx",
          boxed: true,
          message: "数据获取中...",
          zIndex: 10051,
          overlayColor: "#67809F"
        });
        setTimeout(() => {
          this.commservice.unblockUI(".body_bqssxx");
          if (!this.allroadMaker[bqsbid]) {
            //是真的没有数据
          } else {
            const markobj = this.allroadMaker[bqsbid].getExtData(); // 里面没有位置信息
            this.dzbqsb_ssmsg.id = this.commservice.removeSpace(false, markobj.id_n);
            this.dzbqsb_ssmsg.gnssdl = this.commservice.removeSpace(false, markobj.gnssdl);
            this.dzbqsb_ssmsg.lydl = this.commservice.removeSpace(false, markobj.lydl);
            this.dzbqsb_ssmsg.sj = this.commservice.removeSpace(false, markobj.sj);
            this.getAddresss(markobj.position, (resp) => {
              this.dzbqsb_ssmsg.dzmc = resp.regeocode.formattedAddress;
            });
          }
        }, 10000);
      } else {
        this.hander_dzbqsbssmsg(bqsbid, 'reload');
      }
    } else {
      const markobj = this.allroadMaker[bqsbid].getExtData(); // 里面没有位置信息
      this.dzbqsb_ssmsg.id = this.commservice.removeSpace(false, markobj.id_n);
      this.dzbqsb_ssmsg.gnssdl = this.commservice.removeSpace(false, markobj.gnssdl);
      this.dzbqsb_ssmsg.lydl = this.commservice.removeSpace(false, markobj.lydl);
      this.dzbqsb_ssmsg.sj = this.commservice.removeSpace(false, markobj.sj);
      this.getAddresss(markobj.position, (resp) => {
        this.dzbqsb_ssmsg.dzmc = resp.regeocode.formattedAddress;
      });
    }
  }

  /**
   * 显示标签关联的试卷包信息
   * @param item
   */
  showSjbxx(item: any): void {
    this.xqobj_sjbxx = {
      from: "zdsb_glbqsb_sjbxx",
      keyValue: {
        sjbsjxxList: item.sjbgllist
      }
    };
    $("#xq_kglbqsjbModal").modal({
      keyboard: true,
      backdrop: "static"
    });
  }

  /**
   * 关闭win
   * @param {string} flag
   * rw---任务详情
   * zdsb--终端设备详情
   */
  closeWin(flag: string): void {
    if (flag == "rw") {
      $(".rw_glsjxx").hide();
    } else if (flag == "zdsb") {
      $(".zdsb_glsjxx").hide();
    } else if (flag == "dzbqsb") {
      $(".dzbqsb_xx").hide();
    }
  }

  /**
   * 设置该任务的出发地 和  目的地  的marker位置
   * @param cfdposition
   * @param mddposition
   */
  setPositionDZ(cfdmc: string, cfdposition: any, mddmc: string, mddposition: any): void {
    this.cfdMarker.show();
    this.mddMarker.show();
    this.cfdMarker.setPosition(cfdposition);
    this.cfdMarker.setLabel({
      content: "<span style='border:none;color:red;'>" + cfdmc + "</span>",
      offset: new AMap.Pixel(-5, 18), //修改label相对于maker的位置(相对marker的左上角)
    });
    this.mddMarker.setPosition(mddposition);
    this.mddMarker.setLabel({
      content: "<span style='border:none;color:red;'>" + mddmc + "</span>",
      offset: new AMap.Pixel(-5, 18), //修改label相对于maker的位置(相对marker的左上角)
    });
  }

  /**
   * 处理页面的相关元素尺寸
   */
  initSize(): void {
    const h = this.commservice.getViewPort().height - this.commservice.topmenuH - this.commservice.topH;
    this.pagesize.pageh = `${h}px`;
    this.pagesize.rpanelwinit = this.commservice.getViewPort().width - this.pagesize.lpanelwinit - 20; //
    this.pagesize.rpanelwstr = `${this.pagesize.rpanelwinit}px`;
  }

  /**
   * 1---左侧控制
   * msg--右下角的消息控制
   */
  lpanelCtr(flag: string): void {
    if (flag == "l") {
      const lshow = this.pagesize.lpanelshow;
      if (lshow) {
        this.pagesize.lpanelshow = false;
        $(".lpanel").animate({
          width: 20
        }, 500);
        this.pagesize.rpanelwinit = this.pagesize.rpanelwinit + (this.pagesize.lpanelwinit - 20);
        this.pagesize.rpanelwstr = `${this.pagesize.rpanelwinit}px`;
        $(".rpanel").animate({
          marginLeft: "20px"
        }, 500);
        $("#lformRoom").hide();
      } else {
        this.pagesize.lpanelshow = true;
        $(".lpanel").animate({
          width: 475
        }, 500);
        this.pagesize.rpanelwinit = this.pagesize.rpanelwinit - (this.pagesize.lpanelwinit - 20);
        this.pagesize.rpanelwstr = `${this.pagesize.rpanelwinit}px`;
        $(".rpanel").animate({
          marginLeft: this.pagesize.lpanelwinit + "px"
        }, 500);
        $("#lformRoom").show();
      }
    } else if (flag == "msg") {
      if (this.warnmsgshow) {
        this.warnmsgshow = false;
        $(".warnmsgDiv").animate({
          width: 20
        }, 500);
        $(".warnmsgDiv>.msgroom").hide();
      } else {
        this.warnmsgshow = true;
        $(".warnmsgDiv").animate({
          width: 250
        }, 500);
        $(".warnmsgDiv>.msgroom").show();
        // 处理滚动插件
        // $('.msgroom').slimScroll({
        //   height: 300,
        //   alwaysVisible: true,
        //   color: "#0050C3",
        //   railColor: "#3598DC",
        //   railVisible: true,
        //   railOpacity: .8
        // });
      }
    }
  }

  /**
   * 查询范围树的 显示与否控制
   */
  searchTreectr(): void {
    this.treeshow = !this.treeshow;
  }

  initMap(): void {
    const that = this;
    this.map = new AMap.Map("mapdiv", {
      resizeEnable: true, //是否监控地图容器尺寸变化，默认值为false
      zoom: 11, //地图显示的缩放级别，若center与level未赋值，地图初始化默认显示用户所在城市范围，没有center（中心点）和level ，所以这个暂时无效
    });
    this.cfdMarker = new AMap.Marker({
      map: this.map,
      offset: new AMap.Pixel(-9, -9),
      visible: false, // 默认不可见，当年点击了 任务详情的时候可见
    });
    this.mddMarker = new AMap.Marker({
      map: this.map,
      offset: new AMap.Pixel(-9, -9),
      visible: false, // 默认不可见，当年点击了 任务详情的时候可见
    });
    this.viewpolygon = new AMap.Polygon({
      map: this.map,
      fillColor: '#80d8ff',
      strokeColor: '#00b0ff',
      strokeWeight: 3,
    });
    this.viewpolygon.hide(); // 默认不显示
    AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', 'AMap.Geocoder', "AMap.GraspRoad"],
      function () {
        //缩放，平易等工具条
        that.map.addControl(new AMap.ToolBar());
        //比例尺
        that.map.addControl(new AMap.Scale());
        //鹰眼
        that.map.addControl(new AMap.OverView({
          isOpen: false
        }));
        that.geocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: "all"
        });
        that.map.addControl(that.geocoder);
        // 轨迹纠偏
        that.graspobj = new AMap.GraspRoad();
      });
    //信息窗口
    const info = [];
    //info.push("<div><div><img style=\"float:left;\" src=\" http://webapi.amap.com/images/autonavi.png \"/></div> ");
    info.push("<div style='padding:0px 0px 0px 4px'><b>" + "--" + "</b>");
    info.push("运送人 : " + "--");
    info.push("运送人电话 : " + "--");
    info.push("目的地 : " + "--");
    info.push("</div>");
    this.mapwin = new AMap.InfoWindow({
      content: info.join("<br/>") //使用默认信息窗体框样式，显示信息内容
    });
  }

  getAddresss(lnglatXY: any, callback: Function): void {
    this.geocoder.getAddress(lnglatXY, function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        callback(result);
      }
    });
  }

  /**
   * 查询表单
   */
  createsearchForm(): void {
    const cxlxData = [{
      code: "sjysrw",
      name: "运送任务"
    }, {
      code: "sczdsb",
      name: "手持终端"
    }, {
      code: "dzbqsb",
      name: "电子标签"
    }];
    $("#cxlxSelect").empty();
    let str: string = "";
    cxlxData.forEach((item) => {
      str += "<option value='" + item.code + "'>" + item.name + "</option>";
    });
    $("#cxlxSelect").append(str);
    $("#cxlxSelect").selectpicker({
      size: 5
    });
    this.s_obj.cxlx = cxlxData[0].code;
  }


  initWarnMsg(): void {
    const servertime = this.localStorageService.get("msgservesj");  // 刚进入该页面的服务器时间
    const lastmsgtime = this.localStorageService.get("msglastsj"); // 最后一条报警信息中返回的事件
    if (!servertime) {
      this.s_obj_warnmsg.lssj = "";
    } else {
      if (!lastmsgtime) {
        this.s_obj_warnmsg.lssj = servertime;
      } else {
        this.s_obj_warnmsg.lssj = lastmsgtime;
      }
    }
    const url = "sjgz/gjcx/cxbjxx";
    this.itservice.kwPtPost(url, this.s_obj_warnmsg).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (arg1, resp, arg2) => {
        if (arg1) {
          if (arg2) {
            const fwqsj = resp.fwqsj;
            if (!this.localStorageService.get('msgservesj')) {
              this.localStorageService.set("msgservesj", fwqsj ? fwqsj : ''); // 不更新一直是第一次请求的服务器时间
            }
            const bjxxList = resp.bjxxList;
            if (bjxxList && bjxxList.length) {
              this.warnmsgList = bjxxList;
              const msglastsjv = bjxxList[0].xxsj;
              this.localStorageService.set("msglastsj", msglastsjv);
              // 如果有新数据返回，则自动显示
              this.warnmsgshow = false;
              this.lpanelCtr('msg');
            } else {
              // 如果有新数据返回，则自动隐藏
              this.warnmsgshow = true;
              this.lpanelCtr('msg');
            }
          } else {

          }
        }
      });
    });
  }

  /**
   * 向终端设备发送消息
   */
  createformgroup_zdsbmsg(): void {
    this.formgroup_zdsbmsg = this.fb.group({
      xxnrCtr: []
    });
  }

  sendMsgtoZdsb(): void {
    const formgroupv = this.formgroup_zdsbmsg.getRawValue();
    const xxnrv = this.commservice.removeSpace(false, formgroupv.xxnrCtr);
    if (xxnrv) {
      this.commservice.blockUI({
        boxed: true,
        message: "保存中...",
        zIndex: 10051,
        overlayColor: "#67809F"
      });
      const url = "sjgz/sbpz/xfxxtz";
      this.itservice.kwPtPost(url, {
        xxnr: xxnrv,
        id: this.caozuoid_n
      }).subscribe(resp => {
        this.commservice.handResponse("put", url, resp, (arg1, resp, arg2) => {
          if (arg1) {
            if (arg2) {
              this.commservice.myswal("success", resp, "", "ts", null);
              $("#send_msgModal").modal("hide");
            } else {
              this.commservice.myswal("warning", resp, "", "ts", null);
            }
          } else {
            this.sendMsgtoZdsb();
          }
        });
      });
    }
  }

  /**
   * 对经纬度坐标做点平滑处理
   * @param arr
   * @param {number} phd  ---平滑度
   * @returns {any}
   */
  handPH(arr: any, phd: number): any {
    const pharr: any = [];
    arr.forEach((item, index) => {
      const jdlist: any[] = [];
      const wdlist: any[] = [];
      for (let i = index; i < (Number(phd) + Number(index)); i++) {
        if (i < arr.length) {
          jdlist.push(arr[i][0]);
          wdlist.push(arr[i][1]);
        }
      }
      const phjd = this.commservice.sum(jdlist) / jdlist.length;
      const phwd = this.commservice.sum(wdlist) / wdlist.length;
      pharr.push([phjd, phwd])
    });
    // console.log("平滑后的数据", phd, pharr);
    return pharr;
  }

  /**
   * 获取用户信息
   */
  getuserinfo(): void {
    this.commservice.getUserinfo((info) => {
      this.userinfo = info;
      const userrole = this.commservice.getuserDepartmentFl(info.cslx, info.csid, info.nowrolecode);
      if (userrole === "Z3") {
        this.s_obj.ksgljgid = info.csid;
        this.s_obj.ksgljgidmc = info.csmc;
        this.search_n();
      } else if (userrole === "Z1" || userrole === "Z2") {
        this.initsearchTree();
      }
    });
  }


  constructor(private commservice: CommService,
              private itservice: MyhttpService,
              private localStorageService: LocalStorageService,
              private cfr: ComponentFactoryResolver,
              private fb: FormBuilder) {

  }

  ngOnInit() {
    this.s_obj.ksjhbh = this.localStorageService.get("hksjh");
    this.commservice.getSysmsg2((resp) => {
      this.sysBase = resp.sysBase;
    });
    this.initSize();
    this.initMap();
    this.createsearchForm();
    this.getuserinfo();
    this.createformgroup_zdsbmsg();
    this.s_obj_warnmsg.ksjhbh = this.s_obj.ksjhbh;
    this.initWarnMsg();
    this.lockid_warnmsg = setInterval(() => {
      this.initWarnMsg();
    }, this.intervalnum_warnmsg);
  }

  ngOnDestroy() {
    if (this.lockid) {
      clearInterval(this.lockid);
    }
    if (this.lockid_warnmsg) {
      clearInterval(this.lockid_warnmsg);
    }
  }

}
